zoukankan      html  css  js  c++  java
  • 11. Minimum Depth of Binary Tree 11.二叉树的最小深度

    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
  • 相关阅读:
    sql server delete语句
    sql server 通配符
    sql server join联结
    windows下如何使用两个版本的nodejs
    PHP的Trait 特性
    PHP错误与异常处理try和catch
    laravel belongsTo()&hasOne()用法详解
    Laravel Model 的 fillable (白名单)与 guarded (黑名单)
    js原生,缓动动画封装
    js原生轮播图
  • 原文地址:https://www.cnblogs.com/immiao0319/p/12995604.html
Copyright © 2011-2022 走看看