python - 查找树的高度,其中输入树可以有任意数量的子树

标签 python recursion tree tuples

我的问题的一部分是编写一个确定树高度的函数。

这是我当前的功能,

def tree_height(node): 
  parent, children = node
  max_height = 0
  for child in children:
    height = tree_height(child)
    if height > max_height:
      max_height = height
  return max_height 

但它只返回0。

* 注意:只能有一个输入参数,即节点 *

对于,

tree = ("supercalifragilisticexpialidocious",(("a",(("b",(("candy",()),)),("onomatopoeia",()),)),("d",(("egg",(("f",()),)),)),))

输出应该是,

3

最佳答案

你永远不会增加max_height,因此递归调用将始终返回0;请记住,您比您的 child 高一级。

def tree_height(node): 
    parent, children = node
    max_height = 0
    for child in children:
      child_height = tree_height(child)
      max_height = max(max_height, child_height +  1)
    return max_height

您需要“相信”递归:假设tree_height(child)给出了您 child 的高度。那么您的高度就是您所有 child 的最大高度加一。

编辑:

更Pythonic的代码:

def tree_height(node):
  parent, children = node
  return max([tree_height(child) + 1 for child in children]) if children else 0

关于python - 查找树的高度,其中输入树可以有任意数量的子树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56865582/

相关文章:

python - 用另一列中的相同行值替换 pandas 数据框列中的值

python - 在 Python 中使用 OpenCV 消除切向透视失真

c - 递归不按预期工作

c++ - 尝试使用 C++ 实现检测字符串中回文的递归版本。在这里遇到一些麻烦

当在 C 中接收到 SIGINT 时,在进程树中使用 fork() 创建 X 个子进程

python - 在 python 中通过 SSL 反向 shell

python - Python请求中 "data"和 "params"之间的区别?

c++ - 为什么递归可变参数模板不能按预期工作?

c - C中删除左子树节点(二叉搜索树)

javascript - 使用迭代样式在 JavaScript 中克隆对象