四道题搞懂二叉树深度

二叉树的最大深度(LeetCode104)

先表示左树的深度,再表示右树的深度。再进行条件判断

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

二叉树的最小深度(LeetCode111)

先表示左树的深度,再表示右树的深度。再进行条件判断。这里的条件就是:左右分别为空该怎么样返回。

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);
        if (root.left == null)    return rightDepth + 1;
        if (root.right == null)    return leftDepth + 1;

        return Math.min(leftDepth, rightDepth) + 1;
    }
}

二叉树的直径(LeetCode543)

先表示左树的深度,再表示右树的深度。再进行条件判断。左的深度+右的深度

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

想必你也看出来了,代码都大同小异。

平衡二叉树(LeetCode110)

class Solution {
    private boolean isBalanced;  
    public boolean isBalanced(TreeNode root) {  
        isBalanced = true;  
        dfs(root);  
        return isBalanced;  
    }  
  
    private int dfs(TreeNode root) {  
        if (root == null) {  
            return 0;  
        }  
        int lefDepth = dfs(root.left);  
        int rightDepth = dfs(root.right);  
        if (Math.abs(lefDepth-rightDepth) > 1) {  
            isBalanced = false;  
        }  
        return Math.max(lefDepth,rightDepth) + 1;  
    }  

}

通过这四道题想必你已经理解了二叉树的深度相关问题了(⊙o⊙)~~

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

艺成超爱牛肉爆大虾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值