Python求二叉树的属性(深度、直径等)

文章介绍了如何使用递归方法在LeetCode的两道题目中求解二叉树的最大深度和直径。对于最大深度,通过计算左右子树的最大深度并取最大值加1来得到。而对于直径,需要两次深度优先搜索(DFS)分别计算左右子树的深度,并找到最长路径的长度。

递归得到二叉树的最大深度

参考题目

LeetCode 104. 二叉树的最大深度

实现代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def maxDepth(self, root):
        if root is None: 
            return 0 
        else: 
            left_height = self.maxDepth(root.left) 
            right_height = self.maxDepth(root.right) 
            return max(left_height, right_height) + 1 

递归得到二叉树的直径

参考题目

LeetCode 543. 二叉树的直径

实现代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        def getTreeDepth(root):
            if not root:
                return 0
            leftDepth = getTreeDepth(root.left)
            rightDepth = getTreeDepth(root.right)
            return max(leftDepth, rightDepth) + 1
        
        def dfs(root):
            if not root:
                return
            leftDepth, rightDepth = 0, 0
            if root.left:
                leftDepth = max(leftDepth, getTreeDepth(root.left))
            if root.right:
                rightDepth = max(rightDepth, getTreeDepth(root.right))
            nonlocal res
            res = max(res, leftDepth + rightDepth)
            if root.left:
                dfs(root.left)
            if root.right:
                dfs(root.right)
        
        res = 0
        dfs(root)
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值