记忆点:
前序:VLR 中序:LVR 后序:LRV
举例:
一颗二叉树如下图所示 则它的前序、中序、后序遍历流程如下图所示
前序遍历
class Solution:
def preorderTraversal(self, root: TreeNode):
def preorder(root: TreeNode):
if not root:
return
res.append(root.val)
preorder(root.left)
preorder(root.right)
res = []
preorder(root)
return res
中序遍历
class Solution:
def inorderTraversal(self, root: TreeNode):
def inorder(root: TreeNode):
if not root:
return
inorder(root.left)
res.append(root.val)
inorder(root.right)
res = []
inorder(root)
return res
后序遍历
class Solution:
def postorderTraversal(self, root: TreeNode):
def postorder(root: TreeNode):
if not root:
return
postorder(root.left)
res.append(root.val)
postorder(root.right)
res = []
postorder(root)
return res
测试
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def createTree(root,list_n,i):
if i <len(list_n):
if list_n[i] == 'null':
return None
else:
root = TreeNode(val = list_n[i])
root.left = createTree(root.left,list_n,2*i+1)
root.right = createTree(root.right,list_n,2*i+2)
return root
return root
class Solution:
def preorderTraversal(self, root: TreeNode):
def preorder(root: TreeNode):
if not root:
return
res.append(root.val)
preorder(root.left)
preorder(root.right)
res = []
preorder(root)
return res
def inorderTraversal(self, root: TreeNode):
def inorder(root: TreeNode):
if not root:
return
inorder(root.left)
res.append(root.val)
inorder(root.right)
res = []
inorder(root)
return res
def postorderTraversal(self, root: TreeNode):
def postorder(root: TreeNode):
if not root:
return
postorder(root.left)
postorder(root.right)
res.append(root.val)
res = []
postorder(root)
return res
if __name__ == "__main__":
root = TreeNode()
list_n = [1,2,3,4,5,6,7,8,'null',9,10]
root = createTree(root,list_n,0)
s = Solution()
res_pre = s.preorderTraversal(root)
res_in = s.inorderTraversal(root)
res_post = s.postorderTraversal(root)
print(res_pre)
print(res_in)
print(res_post)
结果
参考
1、python 用列表递归创建二叉树:link. 2、递归式遍历:link.
|