递归
# 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 ):
#递归
self.pre,self.inn,self.post=[],[],[]
self.preorder(root)
self.innorder(root)
self.postorder(root)
return [self.pre,self.inn,self.post]
def preorder(self,root):
if not root:return
self.pre.append(root.val)
self.preorder(root.left)
self.preorder(root.right)
def innorder(self,root):
if not root:return
self.innorder(root.left)
self.inn.append(root.val)
self.innorder(root.right)
def postorder(self,root):
if not root:return
self.postorder(root.left)
self.postorder(root.right)
self.post.append(root.val)
简化在一个函数里就可以:
# 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 ):
#递归
pre,inn,post=[],[],[]
def dfs(root):
if not root:return
pre.append(root.val)
dfs(root.left)
inn.append(root.val)
dfs(root.right)
post.append(root.val)
dfs(root)
return [pre,inn,post]
非递归
利用栈
注意:后序遍历可以按照前序改一下,改为根右左,输出时反过来即为左右根
# 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 ):
#非递归
def preorder(root):
res=[]
if not root: return []
stack=[]
cur=root
while cur or stack:
while cur:
stack.append(cur)
res.append(cur.val)
cur=cur.left
else:
cur=stack.pop()
cur=cur.right
return res
def innorder(root):
res=[]
if not root: return []
stack=[]
cur=root
while cur or stack:
while cur:
stack.append(cur)
cur=cur.left
else:
cur=stack.pop()
res.append(cur.val)
cur=cur.right
return res
def postrorder(root):
res=[]
if not root: return []
stack=[]
cur=root
while cur or stack:
while cur:
stack.append(cur)
res.append(cur.val)
cur=cur.right
else:
cur=stack.pop()
cur=cur.left
return res[::-1]
return [preorder(root),innorder(root),postrorder(root)]