python 实现返回二叉树的高度
以下是 Python 实现返回二叉树高度的代码:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def height(root):
if root is None:
return 0
else:
left_height = height(root.left)
right_height = height(root.right)
return max(left_height, right_height) + 1
# 测试代码
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
print(height(root))
# 输出:3
在这个实现中,我们定义了一个 TreeNode 类,用于创建二叉树的节点。height 函数接受一个二叉树的根节点作为参数,返回该二叉树的高度。如果根节点为空,返回 0。如果根节点非空,则递归计算左子树和右子树的高度,并返回两者中的最大值加 1。最后,我们使用测试代码创建了一个二叉树,并输出它的高度
原文地址: https://www.cveoy.top/t/topic/hgwj 著作权归作者所有。请勿转载和采集!