【重点】【二叉树】543. 二叉树的直径

题目

Python

# 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 __init__(self):
        self.ans = 0
    
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        if root == None:
            return 0

        self.myPath(root)
        return self.ans
    
    def myPath(self, root: Optional[TreeNode]):
        if root == None:
            return 0
        left_path = self.myPath(root.left)
        right_path = self.myPath(root.right)

        self.ans = self.ans if self.ans > left_path + right_path else left_path + right_path
        return 1 + max(left_path, right_path)

Java

法1:自己想的垃圾算法

class Solution {
    public int diameterOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int curDim = maxDepth(root.left) + maxDepth(root.right);
        int leftDim = diameterOfBinaryTree(root.left);
        int rightDim = diameterOfBinaryTree(root.right);

        return Math.max(curDim, Math.max(leftDim, rightDim));
    }

    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }
}

法2:DFS好方法

和求二叉树中最大路径和相同套路
合理利用全局变量, 可以大大简化问题!!!

class Solution {
    int ans = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        maxDepth(root);
        
        return ans;
    }

    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        ans = ans > leftDepth + rightDepth ? ans : leftDepth + rightDepth;
        return 1 + Math.max(leftDepth, rightDepth);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值