11. Minimum Depth of Binary Tree

Posted immiao0319

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了11. Minimum Depth of Binary Tree相关的知识,希望对你有一定的参考价值。

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   /   9  20
    /     15   7

return its minimum depth = 2.

 

结果2 = 左边加1得出来的。
如果是最小值并且一边为空的话,就是0 + 1了,这是不准确的,因为没路的一边其实没用。其实是非空的一侧才长度增加
概括是:有路就找最短,没路就找有路的。这是和最大长度的一个区别。

技术图片
/**
 * Definition for a binary tree node.
 * 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;
 *     }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        //cc
        if (root == null) 
            return 0;
        
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        int min = Math.min(left, right);
        
        if (left == 0) {
            return right + 1;
        }else if (right == 0) {
            return left + 1;
        }else
            return min + 1;
    }
}
View Code

 

以上是关于11. Minimum Depth of Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章

111. Minimum Depth of Binary Tree

LeetCode | Minimum Depth of Binary Tree

[Leetcode] Minimum Depth of Binary Tree

111. Minimum Depth of Binary Tree

111. Minimum Depth of Binary Tree

Minimum Depth of Binary Tree