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
| class Node(): def __init__(self,data,left=None,right=None): self.data = data self.left = left self.right = right
def preorder(BT,list_=[]): if BT: if BT.left==None and BT.right==None: list_.append(BT.data) preorder(BT.left) preorder(BT.right) return list_
tree = Node('a', Node('b', Node('d'), Node('f', Node('e'))), Node('c', Node('g', None, Node('h')), Node('i'))) print(preorder(tree))
def postorderheight(BT): if BT: HLeft = postorderheight(BT.left) HRight = postorderheight(BT.right) MaxH = max(HLeft , HRight) return MaxH +1 else: return 0
print(postorderheight(tree))
tree2 = Node('+',Node('+',Node('a'),Node('*',Node('b'),Node('c'))),Node('*',Node('+',Node('*',Node('d'),Node('e')),Node('f')),Node('g')))
def preorder(BT,list_=[]): if BT: list_.append(BT.data) preorder(BT.left) preorder(BT.right) return ' '.join(list_) def inorder(BT,list_=[]): if BT: list_.append('(') inorder(BT.left) list_.append(BT.data) inorder(BT.right) list_.append(')') return ' '.join(list_) def postorder(BT,list_=[]): if BT: postorder(BT.left) postorder(BT.right) list_.append(BT.data) return ' '.join(list_)
pre = preorder(tree2) print(pre) ino = inorder(tree2) print(ino) post_ = postorder(tree2) print(post_)
''' 用递归的方法 类似先序遍历 去重建二叉树。 ''' class Rebuild(): def reconstructbinarytree(self,pre,tin): return self.rebuild_tree(pre,0,len(pre)-1,tin,0,len(tin)-1)
def rebuild_tree(self,pre,pre_start,pre_end,tin,tin_start,tin_end): if pre_start > pre_end or tin_start > tin_end: return None head = Node(pre[pre_start]) tin_mid = tin.index(pre[pre_start]) left_length = tin_mid - tin_start head.left = self.rebuild_tree(pre,pre_start+1,pre_start+left_length, tin,tin_start,tin_mid-1) head.right = self.rebuild_tree(pre,pre_start+left_length+1,pre_end, tin,tin_mid+1,tin_end) return head
def postorderprint(BT,list_=[]): if BT: postorderprint(BT.left) postorderprint(BT.right) list_.append(BT.data) return list_
pre = ['a', 'b', 'd', 'f', 'e', 'c', 'g', 'h', 'i'] tin = ['d', 'b', 'e', 'f', 'a', 'g', 'h', 'c', 'i'] R = Rebuild() head = R.reconstructbinarytree(pre,tin) print(postorderprint(head))
|