Python中的递归任意树高度

佩纳克

我正在尝试实现一种递归方法来确定任意树而不是二叉树的树高。我们得到两个输入,一个是顶点的个数。第二行包含从-1到n -1个顶点父级的n个整数。如果其中第i个(0≤i≤n − 1)为-1,则顶点i为根,否则为第i个顶点的父级的从0开始的索引。保证只有一个根。确保输入代表一棵树。

例如,输入为:n = 5 parent = [4,-1,4,1,1,1]这意味着节点0是节点4的子代,节点1是根,节点2是节点4的子代。节点3是节点1(根)的子节点,节点4同样是节点1(根)的子节点。自从:

0 1 2 3 4

4 -1 4 1 1

输出将是3的树的高度。我们为慢速方法提供了执行更快的方法的任务。恐怕我看不到如何将节点输入输入到类似以下内容的地方:

Height(tree)
if tree = null:
    return 0
else:
    return 1 + Max(Height(tree.child)) 
    # I realise this is a max of one value

提前致谢!

# python3

import sys, threading

sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27)  # new thread will get stack of such size

n = 5
parent = [4, -1, 4, 1, 1]

class TreeHeight:
    def read(self, n, parent):
        self.n = n
        self.parent = parent

    def compute_height(self):
        # Replace this code with a faster implementation    
        maxHeight = 0

        for vertex in range(self.n):
            height = 0
            i = vertex
            while i != -1:
                height += 1
                i = self.parent[i] 
            maxHeight = max(maxHeight, height);

        return maxHeight;

def main():
    tree = TreeHeight()
    tree.read(n, parent)
    print(tree.compute_height())

threading.Thread(target=main).start()
临时狼

我相信您正在寻找的是备忘录

对于每个节点,幼稚的实现都会查看到根的整个路径,存储该高度,然后一遍又一遍地重新计算它。

使用备忘录,您可以保存已经完成的计算的备忘录:

例如:

节点0具有height 3,但是在发现您已经找到节点4的高度的情况下,因此可以存储该信息(2)。

然后,当您找到节点2的高度时,它的父节点是节点4,您已经知道它是2...,因此节点2的高度必须为3您没有被迫第二次上树并重新计算所有这些值。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章