二叉树的深度

说道二叉树的深度,第一反应就是二叉树的最大深度 , 在 leetcode 上有一道二叉树的最小深度
其实 最大深度 / 最小深度 其实就是根节点到叶子节点的 最大距离 / 最小距离
在这里插入图片描述
总结起来就是:
d e p t h = { 1 + M a t h . m a x ( l e f t D e p t h , r i g h t D e p t h ) 最大深度 1 + M a t h . m i n ( l e f t D e p t h , r i g h t D e p t h ) 最小深度 depth = \begin{cases} 1 + Math.max(leftDepth , rightDepth)& \text{最大深度} \\ 1 + Math.min(leftDepth , rightDepth)& \text{最小深度} \end{cases} depth={1+Math.max(leftDepth,rightDepth)1+Math.min(leftDepth,rightDepth)最大深度最小深度

树节点表达方式

public class TreeNode {
  int val = 0;
  TreeNode left = null;
  TreeNode right = null;
}

二叉树最大深度实现

public class Solution {
    /**
     * @param root TreeNode类 
     * @return int整型
     */
    public int maxDepth (TreeNode root) {
        // write code here
        if (root == null) return 0;
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        return 1 + Math.max(leftDepth,rightDepth);
    }
}

二叉树最小深度实现
需要注意的是,如果存在一个某一个子树为空时,不能认为最小深度是 0 ,
注意: 最小深度 是根节点到叶子节点的 最小距离

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 && root.right != null) 
            return 1 + rightDepth;
        
        // 当一个右子树为空,左不为空,这时并不是最低点
        if(root.left != null && root.right == null) 
            return 1 + leftDepth;
        
        return 1 + Math.min(leftDepth , rightDepth);
    }
}
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值