创建如下二叉树:
代码如下
#coding:utf-8 class Node(object): ‘‘‘构造节点‘‘‘ def __init__(self,data=None,lchild=None,rchild=None): self.data = data self.lchild = lchild self.rchild = rchild class Tree(object): def __init__(self): self.root = Node() def addNode(self,data): ‘‘‘利用队列构造树‘‘‘ node = Node(data) if self.root.data == None: self.root = node else: myqueue = [] treeNode = self.root myqueue.append(treeNode) while myqueue: treeNode = myqueue.pop(0) if treeNode.lchild == None: treeNode.lchild = node return elif treeNode.rchild == None: treeNode.rchild = node return else: myqueue.append(treeNode.lchild) myqueue.append(treeNode.rchild) def xianxu_digui(self,root): ‘‘‘利用递归实现先序遍历‘‘‘ if root == None: return root else: print(root.data,end=‘ ‘) self.xianxu_digui(root.lchild) self.xianxu_digui(root.rchild) def front_stack(self, root): """利用栈实现二叉树的先序遍历""" if root == None: return mystack = [] node = root while node or mystack: while node: # 从根节点开始,一直找它的左子树 print(node.data, end=‘ ‘) mystack.append(node) node = node.lchild node = mystack.pop() # node = node.rchild # def zhongxu_digui(self,root): ‘‘‘利用递归实现中序遍历‘‘‘ if root == None: return root else: self.zhongxu_digui(root.lchild) print(root.data,end=‘ ‘) self.zhongxu_digui(root.rchild) def midd_stack(self, root): ‘‘‘利用栈实现中序遍历‘‘‘ if root == None: return mystack = [] node = root while node or mystack: while node: mystack.append(node) node = node.lchild node = mystack.pop() print(node.data, end=‘ ‘) node = node.rchild def houxu_digui(self,root): ‘‘‘利用递归实现后序遍历‘‘‘ if root == None: return else: self.houxu_digui(root.lchild) self.houxu_digui(root.rchild) print(root.data,end=‘ ‘) def later_stack(self, root): """利用栈实现后序遍历""" if root == None: return mystack1 = [] # mystack1 这是一个中介栈,目的是调整进mystack2 栈的顺序。 mystack2 = [] #该栈里面的元素是 逆序的倒序,逐个弹出,访问 node = root mystack1.append(node) while mystack1: node = mystack1.pop() mystack2.append(node) if node.lchild: mystack1.append(node.lchild) if node.rchild: mystack1.append(node.rchild) while mystack2: # 将mystack2中的元素逐个弹出,即为后序遍历次序 print(mystack2.pop().data,end=‘ ‘) def leve_queue(self,root): ‘‘‘按层遍历‘‘‘ if root == None: return else: myqueue = [] node = root myqueue.append(root) while myqueue: node = myqueue.pop(0) print(node.data,end=‘ ‘) if node.lchild: myqueue.append(node.lchild) if node.rchild: myqueue.append(node.rchild) tree = Tree() tree.addNode(1) tree.addNode(2) tree.addNode(3) tree.addNode(4) tree.addNode(5) tree.addNode(6) tree.addNode(7) tree.addNode(8) tree.addNode(9) tree.addNode(10) # print(‘先序遍历‘) tree.xianxu_digui(tree.root) print(‘\n‘) tree.front_stack(tree.root) print(‘\n‘) print(‘中序遍历 ‘) tree.zhongxu_digui(tree.root) print(‘\n‘) tree.midd_stack(tree.root) print(‘\n‘) print(‘后序遍历‘) tree.houxu_digui(tree.root) print(‘\n‘) tree.later_stack(tree.root) print(‘\n‘) print(‘层次遍历‘) tree.leve_queue(tree.root)
时间: 2024-10-07 18:49:56