题目:给出一个堆的中序遍历的序列,重建这个堆。 主要是要设计好函数的参数与返回值。
解答:
class Node():
def __init__(self, val):
self.val = val
self.rChild = None
self.lChild = None
a = [3, 2, 4, 1, 3, 5,7,9]
def stack(left, remain, flag):
if left == None and len(remain) > 0:
left = Node(remain[0])
remain = remain[1:]
if len(remain) == 0:
return (left, [])
else:
tmp = Node(remain[0])
remain = remain[1:]
if tmp.val > left.val:
left.rChild, remain = stack(tmp, remain, left.val)
return stack(left, remain, 0)
else:
if tmp.val < flag:
remain = [tmp.val] + remain
return left, remain
tmp.lChild = left
tmp.rChild, remain = stack(None, remain, tmp.val)
return stack(tmp, remain, 0)
def midWalk(node):
if node == None:
return
midWalk(node.lChild)
print node.val
midWalk(node.rChild)
(node, remain) = stack(None, a, 0)
midWalk(node)