zoukankan      html  css  js  c++  java
  • [Leetcode 10] 111 Minimum Depth of Binary Tree

    Problem:

    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.

    Analysis:

    This problem is quite easy. When we compute the height of a binary tree, we use 1 + max(left_height, right_height) recursivly. So the height of a binary tree is actually the maximum depth of this tree. So to get minimum depth, we change max to min to have the following formular 1 + min (left_height, right_height) computed recursively.

    One problem here is that height must be the distance from root to leaf. This implies that the following two trees :[1 2] and [1 # 2] has the height of 2 rather than one. We need to omit those null leaf nodes while computing

    Code:

    View Code
     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public int minDepth(TreeNode root) {
    12         // Start typing your Java solution below
    13         // DO NOT write main() function
    14         if (root == null)
    15             return 0;
    16         else if (root.left==null && root.right==null)
    17             return 1;
    18         else if (root.left==null && root.right!=null)
    19             return 1 + minDepth(root.right);
    20         else if (root.left!=null && root.right==null)
    21             return 1 + minDepth(root.left);
    22         else
    23             return 1 + min(minDepth(root.left), minDepth(root.right));
    24     }
    25     
    26     private int min(int a, int b) {
    27         return (a>b) ? b : a;
    28     }
    29 }

    Attention:

    The minimum depth of a binary tree must from root to some not-null leaf nodes. See the definition clearly.!

  • 相关阅读:
    [bzoj5483][Usaco2018 Dec]Balance Beam_凸包_概率期望
    [bzoj3829][Poi2014]FarmCraft_树形dp
    [bzoj3420]Poi2013 Triumphal arch_树形dp_二分
    [bzoj4240]有趣的家庭菜园_树状数组
    [CF9D]How Many Trees?_动态规划_树形dp_ntt
    拖拽排序
    windows-build-tools
    阿里云七牛云oss获取视频内的帧图片
    转义符输入的转换
    node脚本下载geo数据
  • 原文地址:https://www.cnblogs.com/freeneng/p/3011684.html
Copyright © 2011-2022 走看看