首页 > 其他分享 >二叉树的最小深度

二叉树的最小深度

时间:2022-10-05 23:46:14浏览次数:43  
标签:minDepth 最小 二叉树 深度 null root 节点

二叉树的最小深度

一、题目描述

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

输入:root = [3,9,20,null,null,15,7]
输出:2


输入:root = [2,null,3,null,4,null,5,null,6]
输出:5

二、解题思路

树的问题一般是选用递归的方式来解决。

三、递归调用(深度优先)

首先是根为空,返回0,左右子树为空返回1。其余只需要判断是否有左右子树。一直到为null为止。
代码实现

class Solution {
    public int minDepth(TreeNode root) {

        ##根节点为空
        if(root == null){
            return 0;
        }
        ##根的左右子节点为空
        if(root.left == null && root.right == null){
            return 1;
        }
        ## 设置一个最大值,由于需要求最小深度。
        int minDepth = Integer.MAX_VALUE;
        
        if(root.left != null){
            minDepth = Math.min(minDepth(root.left),minDepth);
        }

        if(root.right != null){
            minDepth = Math.min(minDepth(root.right),minDepth);
        }

        return minDepth+1;
    }
    
}

标签:minDepth,最小,二叉树,深度,null,root,节点
From: https://www.cnblogs.com/zjjtt/p/16756788.html

相关文章