【问题标题】:Getting the height of a tree with a recursive function使用递归函数获取树的高度
【发布时间】:2019-07-19 03:08:53
【问题描述】:

我想解决关于获取树高的 cousera 作业。它要求我使用递归函数获取高度。我写了这个函数,但我仍然没有得到。第一行的输入是节点的数量,第二行是一个数字列表,每个数字都指向该节点的父节点的索引(-1 值表示该节点是根节点)。

我尝试打印max_height,它给了我一个数字列表。当我调试它时,我看到它首先作为例外工作,但在流程返回时,值会在中间发生变化。

def compute_height(n, parents, postion=0, hight=0, max_hight=0, current=0):

    if postion == n-1:
        print(max_hight)
        return max_hight

    if current != -1:
        compute_height(n, parents, postion, hight+1,
                       max(max_hight, hight), parents[current])

    compute_height(n, parents, postion+1, 0, max_hight, postion+1)

它返回None。我该如何解决这个问题?

【问题讨论】:

  • 输入和预期输出是什么?
  • 第一行:5,第二行:4 -1 4 1 1 输出(应该):3

标签: python python-3.x recursion tree


【解决方案1】:

您似乎被递归函数卡住了,不知道如何前进。为了以有效的方式完成这项任务,我对其进行了相当大的更改。

一般来说,要解决此类问题,就效率而言,最重要的是要有一种方法跟踪你已经在哪里,这样你就不 重复不必要的工作。您还需要确保访问树的每一片叶子,因为您不知道哪一片叶子最深。

这里还用到了两个明显相关的函数。第一个是 driver(1) 函数,当你有一个 recursive(2) 函数并想用一组特定的参数调用它来启动它时,它通常很有帮助离开。或者当你想像我在这里一样在 for 循环中运行它时。

如果有什么不明白的地方请告诉我:

# Computes the height of the tree
def compute_height(n, parents):
    # We make a list to keep track of which nodes have already been visited
    heights = [-1 for x in range(n)]

    # Make sure you visit every node if it is not already visited
    for i, val in enumerate(heights):
        if (val == -1):
            recurse_compute_height(n, parents, i, heights)

    return(max(heights))

# Recursively computes the height for the current node 
def recurse_compute_height(n, parents, index, heights):
    parent = parents[index]

    # Base case for when you reach the root
    if parent == -1:
        return 1

    # Leverage the parent's height, if already computed
    if (heights[parent] != -1):
        heights[index] = heights[parent] + 1
    # Or compute the node's and its parents's height
    else:
        heights[index] = recurse_compute_height(n, parents, parent, heights) + 1

    return heights[index]

# Input and run 
n = 5 
parents = [4, -1, 4, 1, 1, 0]
res = compute_height(n, parents)
print(res)

输出

3

【讨论】:

  • 非常感谢你真的帮助了我,我明白了,但是我怎样才能自己解决这些问题,我该怎么办或我应该读什么,再次感谢你:)
  • @MahmoudZeyada 这就是我在代码之前添加描述的原因,这样您就可以了解我的思维过程并了解我为什么这样做。我会建议您继续尝试解决此类问题。这对你来说似乎有点高水平,所以也许从更简单的问题开始,然后在你感到更有信心和学习更多的时候转向更难的问题。一个很好的网站是hackerrank.com。还可以观看有关让您感到困惑的事情的视频!
  • 顺便说一句,我修改了我的解决方案,但评估结果需要很长时间,您的解决方案很棒,但是当 n = 100000 考虑到我在其他线程中运行脚本时,它会导致分段错误max_stack = 3**27
  • @MahmoudZeyada 那你最后有没有找到解决问题的方法呢?
  • 是的,我在没有任何递归调用的情况下使用了 for 循环,它可以工作,但它超过了 10 秒的时间限制,注意我编写了整个测试用例并在我的本地机器上测试它
猜你喜欢
  • 2013-12-08
  • 2018-05-06
  • 2018-09-16
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 2022-10-15
相关资源
最近更新 更多