赞
踩
class TreeNode(object): #创建树的结构 def __init__(self,x): self.val=x self.left=None self.right=None #递归形式 #前序遍历 def preOrderRecusive(root): if root==None: return None print(root.val) preOrderRecusive(root.left) preOrderRecusive(root.right) #中序遍历 def midOrderRecusive(root): if root==None: return None midOrderRecusive(root.left) print(root.val) midOrderRecusive(root.right) #后序遍历 def lateOrderRecusive(root): if root==None: return None lateOrderRecusive(root.left) lateOrderRecusive(root.right) print(root.val) #非递归形式 #前序遍历 def preOrder(root): if root==None: return None tmp=root stack=[] while tmp or stack:#当tmp非空或者stack非空 while tmp: print(tmp.val) stack.append(tmp) tmp=tmp.left node=stack.pop() tmp=node.right#要去循环的下一个头 #中序遍历 def midOrder(root): if root==None: return None tmp=root stack=[] while tmp or stack:#当tmp非空或者stack非空 while tmp: #print(tmp.val) stack.append(tmp) tmp=tmp.left node=stack.pop() print(node.val) tmp=node.right#要去循环的下一个头 #后序遍历 def lateOrder(root): if root==None: return None tmp=root stack=[] while tmp or stack:#当tmp非空或者stack非空 while tmp: #print(tmp.val) stack.append(tmp) tmp=tmp.left node=stack[-1] tmp=node.right#要去循环的下一个头 if node.right==None: node=stack.pop() print(node.val) while stack and node==stack[-1].right: node=stack.pop() print(node.val) #创建一棵树 if __name__=='__main__': t1=TreeNode(1) t2 = TreeNode(2) t3 = TreeNode(3) t4 = TreeNode(4) t5 = TreeNode(5) t6 = TreeNode(6) t7 = TreeNode(7) t1.left=t2 t1.right=t3 t2.left=t4 t2.right=t5 t3.left=t6 t3.right=t7 lateOrder(t1)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。