0
点赞
收藏
分享

微信扫一扫

LeetCode 543. 二叉树的直径

kolibreath 2022-02-09 阅读 87

https://leetcode-cn.com/problems/diameter-of-binary-tree/

二叉树的直径, 可以理解为左子树的深度加上右子树的深度
当前节点的深度为 左/右子树深度 + 1

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

        return Math.max(left, right) + 1;
    }
举报

相关推荐

0 条评论