101-二叉树的最小深度

二叉树的最小深度

题目描述

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

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

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

示例:

给定二叉树 [3,9,20,null,null,15,7],

3

/

9 20

/

15 7

返回它的最小深度 2.

https://leetcode-cn.com/problems/minimum-depth-of-binary-tree

思路

(0)树形DP思想

(1)当前节点是否由左右子节点决定

(2)根据左右节点的结果,怎么计算当前节点的结果

(3)最后将当前节点结果返回

注意

可能会出现只有左节点或只有右节点的情况,所以做好判空

if(root.left != null) 和 if(root.right != null),只有某一节点就不让另一节点参与计算即可

代码

public int minDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        if(root.left == null && root.right == null) {
            return 1;
        }
        int leftMinDepth = Integer.MAX_VALUE;
        int rightMinDepth = Integer.MAX_VALUE;
        if(root.left != null) {
            leftMinDepth = minDepth(root.left);
        }  
        if(root.right != null) {
            rightMinDepth = minDepth(root.right);
        }
        int minDepth = Math.min(leftMinDepth, rightMinDepth);
        return minDepth + 1;
    }
原文地址:https://www.cnblogs.com/boycelee/p/13636132.html