leetcode每日一题-111. 二叉树的最小深度

1、问题

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明:叶子节点是指没有子节点的节点。
在这里插入图片描述

2、思路

我们利用递归的方式来解决,利用DBS深度优先算法来便利所有树叶的节点来寻找最小深度的叶子节点。而用到递归就需要考虑递归的三要素:1、明确递归终止条件;2、给出递归终止时的处理办法;3、提取重复的逻辑,缩小问题规模。所以我们设置终止条件就是树节点数量为0或者1的时候,而return反应的就是递归的终止处理的方式,最后的重复逻辑就是各个判断条件。

复杂度分析

时间复杂度:O(N),其中 N 是树的节点数。对每个节点访问一次。

空间复杂度:O(H),其中 H 是树的高度。空间复杂度主要取决于递归时栈空间的开销,最坏情况下,树呈现链状,空间复杂度为 O(N)。平均情况下树的高度与节点数的对数正相关,空间复杂度为 O(logN)。

3、代码

public class TreeNode {
    
    
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {
    
    }
    TreeNode(int val) {
    
     this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
    
    
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
public class Solution {
    
    
    public int minDepth(TreeNode root) {
    
    
        if(root==null){
    
    
            return 0;
        }
        if (root.left ==null && root.right==null){
    
    
            return 1;
        }
        int min_deepin=Integer.MAX_VALUE;
        if (root.left!=null){
    
    
            min_deepin= Math.min(minDepth(root.left),min_deepin);
        }
        if (root.right!=null){
    
    
            min_deepin=Math.min(minDepth(root.right),min_deepin);
        }
        return min_deepin+1;
    }
    public static void main(String[] args) {
    
    
        int [] rootArray={
    
    2,0,3,0,4,0,5,0,6};
		//说明为什么不使用数组转化为二叉树的方式来解决这个数组存放问题,示例二当中的数组不是那种常规的第i的节点是对应某个节点的左子树或者右子树,与原本的数组转二叉树有一定的出入,所以这里我暂时还没有进行思考如何存放这样的数组。(实力有限)
        TreeNode root=new TreeNode(3);
        TreeNode root1=new TreeNode(9);
        root.left=root1;
        TreeNode root2=new TreeNode(20);
        root.right=root2;
        TreeNode root5=new TreeNode(15);
        root2.left=root5;
        TreeNode root6=new TreeNode(7);
        root2.right=root6;
        Solution solution = new Solution();
        System.out.println(solution.minDepth(root));

    }
}

4、知识点

integer无法包含null:

	System.out.println(Integer.parseInt(null));	

//报错
Exception in thread "main" java.lang.NumberFormatException: null
	at java.lang.Integer.parseInt(Integer.java:542)
	at java.lang.Integer.parseInt(Integer.java:615)
	at com.haven.leetcode.leetcode111.Solution.main(Solution.java:21)

会报数组格式出错

猜你喜欢

转载自blog.csdn.net/qq_40500099/article/details/126737868