#输入一个二叉树的根结点,求树的深度。从根结点到叶结点依次经过的结点形成树的一条路径,最长路径的长度为树的深度
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
root = TreeNode(8)
root.left = TreeNode(8)
root.right = TreeNode(7)
root.left.left = TreeNode(9)
root.left.right = TreeNode(2)
root.left.right.left = TreeNode(4)
root.left.right.right = TreeNode(7)
def TreeDepth(pRoot):
if pRoot is None:
return 0
lDepth = TreeDepth(pRoot.left)
rDepth = TreeDepth(pRoot.right)
return max(lDepth,rDepth) + 1
print(TreeDepth(root))
二叉树的深度--python
最新推荐文章于 2025-09-16 19:43:21 发布
本文介绍了一种计算二叉树深度的方法,通过递归遍历左子树和右子树,找到最长路径的长度即为树的深度。示例代码展示了如何创建一个二叉树并调用TreeDepth函数计算其深度。
9万+

被折叠的 条评论
为什么被折叠?



