首先是树的建立:
class TreeNode: def __init__(self,x,left=None,right=None): self.val=x self.left=left self.right=right
t7=TreeNode(7);t8=TreeNode(8)
t3=TreeNode(3);t4=TreeNode(4,t7,right=None);t5=TreeNode(5,left=None,right=t8);t6=TreeNode(6)
t1=TreeNode(1,t3,t4);t2=TreeNode(2,t5,t6)
root=TreeNode(0,t1,t2)
建立好的树如图所示:
一、递归版的遍历(很好记)
class traveral: def __init__(self): self.pre_res=[] self.in_res=[] self.post_res=[] #先序遍历(根左右) def preorder(self,root): if root is None: return None self.pre_res.append(root.val) self.preorder(root.left) self.preorder(root.right) #中序遍历(左根右) def inorder(self,root): if root is None: return None self.inorder(root.left) self.in_res.append(root.val) self.inorder(root.right) #后序遍历(左右根) def postorder(self,root): if root is None: return None self.postorder(root.left) self.postorder(root.right) self.post_res.append(root.val) tra=traveral() tra.preorder(root) tra.inorder(root) tra.postorder(root) print(tra.pre_res) print(tra.in_res) print(tra.post_res)
输出:
[0, 1, 3, 4, 7, 2, 5, 8, 6]
[3, 1, 7, 4, 0, 5, 8, 2, 6]
[3, 7, 4, 1, 8, 5, 6, 2, 0]
二、非递归版本
class non_recursive: def preorder(self,root): stack=[] pre_res=[] while root or stack: while root: pre_res.append(root.val) stack.append(root) root=root.left if stack: t=stack.pop() root=t.right return pre_res def inorder(self,root): stack=[] in_res=[] while stack or root: while root: stack.append(root) root=root.left if stack: t=stack.pop() in_res.append(t.val) root=t.right return in_res def postorder(self,root): stack1=[] stack2=[] post_res=[] stack1.append(root) while stack1: t=stack1.pop() if t.left: stack1.append(t.left) if t.right: stack1.append(t.right) stack2.append(t) while stack2: post_res.append(stack2.pop().val) return post_res def levelorder(self,root): queue=[root] level_res=[] while queue: t=[] for i in range(len(queue)): cur=queue.pop(0) t.append(cur.val) if cur.left: queue.append(cur.left) if cur.right: queue.append(cur.right) level_res.append(t) return level_res nonre=non_recursive() print(nonre.preorder(root)) print(nonre.inorder(root)) print(nonre.postorder(root)) print(nonre.levelorder(root))
输出:
[0, 1, 3, 4, 7, 2, 5, 8, 6]
[3, 1, 7, 4, 0, 5, 8, 2, 6]
[3, 7, 4, 1, 8, 5, 6, 2, 0]
[[0], [1, 2], [3, 4, 5, 6], [7, 8]]
原文:https://www.cnblogs.com/xiximayou/p/11628898.html