zoukankan      html  css  js  c++  java
  • lintcode155- Minimum Depth of Binary Tree- easy

    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.

     Example

    Given a binary tree as follow:

      1
     /  
    2   3
       / 
      4   5
    

    The minimum depth is 2.

    分治法来做,返回左右小的深度+1。

    1.注意处理一侧子树为空的情况,不能就断言最短深度是1了,因为定义要求你一定要下到叶子节点。

    /**
     * Definition of TreeNode:
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left, right;
     *     public TreeNode(int val) {
     *         this.val = val;
     *         this.left = this.right = null;
     *     }
     * }
     */
    
    
    public class Solution {
        /*
         * @param root: The root of binary tree
         * @return: An integer
         */
        public int minDepth(TreeNode root) {
            // write your code here
            if (root == null) {
                return 0;
            }
            
            int left = minDepth(root.left);
            int right = minDepth(root.right);
            
            // 切记处理一侧为空的情况,因为定义一定要走到叶子节点,所以此时不能就返回min = 1。以下处理即把0的那个排除掉。
            if (left == 0 || right == 0) {
                return 1 + Math.max(left, right);
            }
            
            return 1 + Math.min(left, right);
        }
    }
  • 相关阅读:
    Cannot attach the file *.mdf as database
    frameset frame 实例和用法 转
    remove element
    伸展树--java
    Remove Duplicates from Sorted Array
    merge two sorted lists
    valid parentheses
    Longest Common Prefix
    palindrome number(回文数)
    Two Sum
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7659177.html
Copyright © 2011-2022 走看看