04Leetcode每日一题——二叉树的直径

04Leetcode每日一题——二叉树的直径

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。

代码

class Solution {
    public int diameterOfBinaryTree(TreeNode root) {
        if(root == null) return 0;
        int leftResult = (root.left==null)?0:diameterOfBinaryTree(root.left);
        int rightResult = (root.right==null)?0:diameterOfBinaryTree(root.right);
        int result = (root.left!=null || root.right != null) ? 1:0;
        if(root.left!=null && root.right != null){
            result = findDepth(root.left) + findDepth(root.right) + 2;
        }
        int depth = findDepth(root);
        result = Math.max(result, leftResult);
        result = Math.max(result, rightResult);
        result = Math.max(result, depth);
        return result;
    }
    public int findDepth(TreeNode node){
        if(node.left == null && node.right == null) return 0;
        int leftDepth = 0;
        int rightDepth = 0;
        leftDepth = (node.left==null)?leftDepth:1+findDepth(node.left);
        rightDepth = (node.right==null)?rightDepth:1+findDepth(node.right);
        return Math.max(leftDepth, rightDepth);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值