在Python3.x中构建具有序遍历和预序遍历的树

2024-04-19 05:42:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用preorder和inorder遍历(ints列表)构建一个树。以下是我目前所掌握的情况:

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)]

我相信这个算法是正确的,尽管我可能是错的。在

我的问题是-在什么时候我要将项目插入到树中? 我编写了一个类来处理这个问题,只是不确定该在哪里插入这个调用,因为函数将递归地操作。如果有任何关于如何将节点插入树中的建议,我们将不胜感激。在


Tags: inbuildrighttree列表returndefcount
1条回答
网友
1楼 · 发布于 2024-04-19 05:42:46
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)

像那样的?在

相关问题 更多 >