LeetCode刷题笔记 111.二叉树的最小深度

本文深入探讨了计算二叉树最小深度的算法实现,提供了两种不同的解决方案,并附带详细的代码示例。通过递归方式,算法能够有效找出从根节点到最近叶子节点的最短路径上的节点数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目总结

给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

总结

dc算是提供一种解题思路吧(逃~)

Sample Code

class Solution {
    public static int minDepth(TreeNode root) {
        if (root == null) return 0;
        return minDepth1(root);
    }
   public static int minDepth1(TreeNode root) {
        if (root == null) return Integer.MAX_VALUE;	//把单边没有的单边排除,下面处理两边都没有的
        if(root.left == null && root.right ==null) return 1;
        int left_height = minDepth1(root.left);
        int right_height = minDepth1(root.right);
        return Math.min(left_height, right_height) + 1;
    }
}
/**第二种**/
class Solution {
    public int minDepth(TreeNode root) {
        if(root == null){
            return 0;
        }else if(root.left == null){
            return minDepth(root.right) + 1;
        }else if(root.right == null){
            return minDepth(root.left) + 1;
        }else{
            return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
        }
    } 
}

Demo Code

class Solution {
    List<Integer> list = new ArrayList();
    public int minDepth(TreeNode root) {
        if(root == null) return 0;     
        find_add(root, 1);
        return Collections.min(list);
    }
    
    public void find_add(TreeNode n, int len) {
        if(n == null) return;
        if(n.left == null && n.right == null) {
            list.add(len);
            return;    
        }
        find_add(n.left, len+1);
        find_add(n.right, len+1);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值