python - 求树的高度,输入树可以有任意数量的孩子
问题描述
我的部分问题是编写一个确定树高度的函数。
这是我目前的功能,
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;请记住,您比您的孩子高一级。
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)
给了你孩子的身高。那么你的身高就是你所有孩子的最大身高加一。
编辑:
更 Pythonic 的代码:
def tree_height(node):
parent, children = node
return max([tree_height(child) + 1 for child in children]) if children else 0
推荐阅读
- python - Python:__init__ 期间 map_async 中的多个参数
- c - 检查数字是否存在于同一行或列矩阵中
- excel - Excel VBA 更新后自动打印范围不起作用
- vba - 生成数据透视图时应用“PivotField.Autosort”
- mysql - 字符编码错误的数据库
- node.js - 得到错误 builder.knex(...).queryBuilder is not a function
- c# - ExecuteNonQuery 只工作一次,一次运行删除记录(无异常,无错误)
- r - R:删除行不会为某些 .csv 文件上移数据,但会为 .xls 文件上移
- jquery - 有没有办法做一个|| 或使用 Jquery 的带有单击功能的语句?
- multithreading - 使用 JavaFX 进行无限多线程以更新 GUI