标签:style blog color os 使用 sp for 数据 div
1 class G: 2 def evaluate(self, l, r, v): 3 self.left = l 4 self.right =r 5 self.val = v
构建测试数据:
1 tree = [G() for i in xrange(9)] 2 tree[8].evaluate(None, None, 8) 3 tree[7].evaluate(None, None, 7) 4 tree[6].evaluate(None, None, 6) 5 tree[5].evaluate(None, None, 5) 6 tree[4].evaluate(tree[7], tree[8], 4) 7 tree[3].evaluate(None, None, 3) 8 tree[2].evaluate(tree[5], tree[6], 2) 9 tree[1].evaluate(tree[3], tree[4], 1) 10 tree[0].evaluate(tree[1], tree[2], 0)
先序遍历:
1 def preOrder(t): 2 p = t 3 stack = [] 4 rslt = [] 5 while p or stack: 6 if p: 7 rslt.append(p.val) 8 stack.append(p.right) 9 p = p.left 10 else: 11 p = stack.pop() 12 print rslt
中序遍历:
1 def inOrder(t): 2 p = t 3 stack = [] 4 rslt = [] 5 while p or stack: 6 if p: 7 stack.append(p) 8 p = p.left 9 else: 10 s = stack.pop() 11 rslt.append(s.val) 12 p = s.right 13 print rslt
后序遍历:
1 def postOrder(t): 2 p = t 3 leftStack = [] 4 rightStack = [] 5 rslt = [] 6 while (p or leftStack or rightStack): 7 if p: 8 leftStack.append(p) 9 p = p.left 10 elif leftStack and rightStack and leftStack[-1] == rightStack[-1]: 11 leftStack.pop().val 12 rslt.append(rightStack.pop().val) 13 else: 14 rightStack.append(leftStack[-1]) 15 p = leftStack[-1].right 16 print rslt
标签:style blog color os 使用 sp for 数据 div
原文地址:http://www.cnblogs.com/pypot/p/4103543.html