二叉树的最小深度

二叉树的最小深度

一、题目描述

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

输入: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;
    }
    
}
posted @ 2022-10-05 23:31  z_coding  阅读(32)  评论(0)    收藏  举报