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

  • 相关阅读:
    经典脚本集合
    Crystal Report 注册号
    Linux top命令简介
    sysctl.conf优化方案(完整)
    vi入门学习(转载)
    linux 如何查看目录的剩余空间大小?
    python3安装pip3
    jsonCpp的readme文档
    第15天android:使用sqlite
    《mysql必知必会》笔记
  • 原文地址:https://www.cnblogs.com/freeneng/p/3011684.html
Copyright © 2011-2022 走看看