#输入一个二叉树的根结点,求树的深度。从根结点到叶结点依次经过的结点形成树的一条路径,最长路径的长度为树的深度
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
最新推荐文章于 2024-09-03 10:31:55 发布