在Python3.x中使用索引和前序遍历构建树
我正在尝试使用前序和顺序遍历(整数列表)构建一棵树。以下是我到目前为止的情况:在Python3.x中使用索引和前序遍历构建树,python,algorithm,tree,tree-traversal,Python,Algorithm,Tree,Tree Traversal,我正在尝试使用前序和顺序遍历(整数列表)构建一棵树。以下是我到目前为止的情况: 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
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)]
我相信这个算法是正确的,尽管我可能是错的
我的问题是-我应该在什么时候将项目插入到树中?
我编写了一个类来处理这个问题,我只是不确定在哪里插入这个调用,因为函数将递归地运行。任何关于如何将节点插入到树中的建议都将不胜感激
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)
像那样的吗?什么?我明白你说的每句话,但我不明白你想做什么。。。而且你的代码并不是那么有启发性的
root=preorder[0]
就是这个地方。其余的看起来不对劲。我不确定在哪里实际插入对我的类的调用,这将使列表项成为一个节点。