描述
分别按照二叉树先序,中序和后序打印所有的节点。
示例1
输入:
{1,2,3}
返回值:
[[1,2,3],[2,1,3],[2,3,1]]
有递归和非递归方法:
递归
# 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 __init__(self):
self.pre_re = []
self.mid_re = []
self.pos_re = []
def pre(self,root):
if root==None:
return
self.pre_re.append(root.val)
if root.left: self.pre(root.left)
if root.right:self.pre(root.right)
def mid(self,root):
if root==None:
return
if root.left: self.mid(root.left)
self.mid_re.append(root.val)
if root.right :self.mid(root.right)
def post(self,root):
if root==None: return
if root.left:self.post(root.left)
if root.right:self.post(root.right)
self.pos_re.append(root.val)
def threeOrders(self , root ):
self.pre(root)
self.mid(root)
self.post(root)
re = [self.pre_re,self.mid_re,self.pos_re]
print(re)
return re
# write code here
非递归
# 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 __init__(self):
self.pre_re = []
self.mid_re = []
self.pos_re = []
def pre(self,root):
visited =[]
val =[]
while root or visited:
while root:
visited.append(root)
val.append(root.val)
root = root.left
if visited:
root = visited.pop()
root = root.right
self.pre_re = val
def mid(self,root):
visited = []
val =[]
while root or visited:
while root:
visited.append(root)
root = root.left
if visited:
root = visited.pop()
val.append(root.val)
root = root.right
self.mid_re = val
def post(self,root):
visited = [root]
val = []
while visited:
node = visited.pop()
val.append(node.val)
if node.left:
visited.append(node.left)
if node.right:
visited.append(node.right)
self.pos_re = val[::-1]
def threeOrders(self , root ):
self.pre(root)
self.mid(root)
self.post(root)
re = [self.pre_re,self.mid_re,self.pos_re]
print(re)
return re
# write code here