1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
| class Node(object): """节点类""" def __init__(self, elem=-1, lchild=None, rchild=None): self.elem = elem self.lchild = lchild self.rchild = rchild
class Tree(object): """树类""" def __init__(self): self.root = Node() self.myQueue = []
def add(self, elem): """为树添加节点""" node = Node(elem) if self.root.elem == -1: self.root = node self.myQueue.append(self.root) else: treeNode = self.myQueue[0] if treeNode.lchild == None: treeNode.lchild = node self.myQueue.append(treeNode.lchild) else: treeNode.rchild = node self.myQueue.append(treeNode.rchild) self.myQueue.pop(0)
def front_digui(self, root): """利用递归实现树的先序遍历""" if root == None: return print root.elem, self.front_digui(root.lchild) self.front_digui(root.rchild)
def middle_digui(self, root): """利用递归实现树的中序遍历""" if root == None: return self.middle_digui(root.lchild) print root.elem, self.middle_digui(root.rchild)
def later_digui(self, root): """利用递归实现树的后序遍历""" if root == None: return self.later_digui(root.lchild) self.later_digui(root.rchild) print root.elem,
def front_stack(self, root): """利用堆栈实现树的先序遍历""" if root == None: return myStack = [] node = root while node or myStack: while node: print node.elem, myStack.append(node) node = node.lchild node = myStack.pop() node = node.rchild
def middle_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.elem, node = node.rchild
def later_stack(self, root): """利用堆栈实现树的后序遍历""" if root == None: return myStack1 = [] myStack2 = [] node = root myStack1.append(node) while myStack1: node = myStack1.pop() if node.lchild: myStack1.append(node.lchild) if node.rchild: myStack1.append(node.rchild) myStack2.append(node) while myStack2: print myStack2.pop().elem,
def level_queue(self, root): """利用队列实现树的层次遍历""" if root == None: return myQueue = [] node = root myQueue.append(node) while myQueue: node = myQueue.pop(0) print node.elem, if node.lchild != None: myQueue.append(node.lchild) if node.rchild != None: myQueue.append(node.rchild)
if __name__ == '__main__': """主函数""" elems = range(10) tree = Tree() for elem in elems: tree.add(elem)
print '队列实现层次遍历:' tree.level_queue(tree.root)
print '\n\n递归实现先序遍历:' tree.front_digui(tree.root) print '\n递归实现中序遍历:' tree.middle_digui(tree.root) print '\n递归实现后序遍历:' tree.later_digui(tree.root)
print '\n\n堆栈实现先序遍历:' tree.front_stack(tree.root) print '\n堆栈实现中序遍历:' tree.middle_stack(tree.root) print '\n堆栈实现后序遍历:' tree.later_stack(tree.root)
|