• [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.!

  • 相关阅读:
    Android之网络数据存储
    Android之ContentProvider数据存储
    类CL_ABAP_TYPEDESCR,动态取得运行时类型
    创建采购订单批到程序用的BAPI
    关于时间的函数
    去非数字字符串的前导零
    abap四舍五入的函数
    读取域的文本表
    PP屏幕增强点
    时间戳计算
  • 原文地址:https://www.cnblogs.com/freeneng/p/3011684.html
Copyright © 2020-2023  润新知