NC45 实现二叉树先序,中序和后序遍历 Python 版本
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/questionTerminal/a9fec6c46a684ad5a3abd4e365a9d362
题目描述
分别按照二叉树先序,中序和后序打印所有的节点
分别按照二叉树先序,中序和后序打印所有的节点
前序:根左右
中序:左根右
后续:左右根
对于顺序的建立。
上代码:
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
#
# @param root TreeNode类 the root of binary tree
# @return int整型二维数组
#
class Solution:
def threeOrders(self, root):
# write code here
pre_order, in_order, post_order = [], [], []
def preorder(root):
if not root:
return None
pre_order.append(root.val)
preorder(root.left)
preorder(root.right)
#根左右
def inorder(root):
if not root:
return None
inorder(root.left)
in_order.append(root.val)
inorder(root.right)
#左根右
def postorder(root):
if not root:
return None
postorder(root.left)
postorder(root.right)
post_order.append(root.val)
#左右根
preorder(root)
inorder(root)
postorder(root)
return [pre_order, in_order, post_order]
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
#
# @param root TreeNode类 the root of binary tree
# @return int整型二维数组
#
class Solution:
def threeOrders(self, root):
# write code here
pre_order, in_order, post_order = [], [], []
def preorder(root):
if not root:
return None
pre_order.append(root.val)
preorder(root.left)
preorder(root.right)
#根左右
def inorder(root):
if not root:
return None
inorder(root.left)
in_order.append(root.val)
inorder(root.right)
#左根右
def postorder(root):
if not root:
return None
postorder(root.left)
postorder(root.right)
post_order.append(root.val)
#左右根
preorder(root)
inorder(root)
postorder(root)
return [pre_order, in_order, post_order]
在线编程答案/牛客题霸 答案(Python版) 文章被收录于专栏
所有在线编程题的详细题解以及答案,Python版。