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
  • 相关阅读:
    GROUP BY 和 ORDER BY一起使用
    MySQL中表的复制以及大型数据表的备份教程
    常用sql
    MySQL 数据类型(float)的注意事项
    MySQL VARCHAR字段最大长度到底是多少
    设计-Int(4)和Int(11)谁更美
    5.Flask-Migrate
    4.alembic数据迁移工具
    3.Flask-SQLAlchemy
    2.Flask jinjia2模板
  • 原文地址:https://www.cnblogs.com/immiao0319/p/12995604.html
Copyright © 2011-2022 走看看