用一段python代码设计函数def get_heightroot计算以root为根的树的高度。请求失败2继续
以下是一段Python代码,实现了计算以root为根的树的高度的功能:
def get_height(root):
if root is None:
return 0
else:
left_height = get_height(root.left)
right_height = get_height(root.right)
return max(left_height, right_height) + 1
其中,root为树的根节点。如果根节点为空,则返回0;否则,递归计算左子树和右子树的高度,取两者中的最大值,并加上1,即为以root为根的树的高度。
原文地址: https://www.cveoy.top/t/topic/bVi9 著作权归作者所有。请勿转载和采集!