用Python3.x根据中序和前序遍历构建树
我正在尝试使用前序遍历和中序遍历来构建一棵树(都是整数的列表)。这是我目前的进展:
def build(preorder, inorder, heap): # Builds tree with the inorder and preorder traversal
if len(preorder) == 0:
return None
root = preorder[0] # Root is first item in preorder
k = root
left_count = inorder[(k-1)] # Number of items in left sub-tree
left_inorder = inorder[0:left_count]
left_preorder = preorder[1:1+left_count]
right_inorder = inorder[1+left_count:]
right_preorder = preorder[1+left_count:]
return [root, build(left_preorder, left_inorder), build(right_preorder, right_inorder)]
我觉得这个算法是正确的,不过我也可能错了。
我想问的是,什么时候把这些元素插入到树中呢?我已经写了一个类来处理这个问题,只是不太确定该在什么地方插入这个调用,因为这个函数会递归运行。任何关于如何将节点插入树中的建议都非常感谢。
1 个回答
1
class heap:
def __init__(self,the_heap):
self.heap = the_heap
def getChildren(self,value):
n = self.heap.index(value)
return self.heap[2*n+1],self.heap[2*n+2] # i think ...
def getParent(self,value):
n = self.heap.index(value)
if n == 0: return None
return self.heap[math.floor(n-1/2.0) ] # i think ...
def traverse(self):
#do your traversal here just visit each node in the order you want
pass
the_heap = heap(range(100))
print the_heap.getChildren(2)
print the_heap.getParent(6)
大概是这个样子吗?