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

  • 相关阅读:
    Python统计excel表格中文本的词频,生成词云图片
    springboot application.properties 常用完整版配置信息
    JAVA高级-面试题总结
    删除csdn上面自己上传的资源
    本博客背景特效源码
    我的自定义框架 || 基于Spring Boot || 第一步
    PYTHON 实现的微信跳一跳【辅助工具】仅作学习
    PM2守护babel-node
    记一个HOST引起的前端项目打不开的问题
    迭代器与iterable
  • 原文地址:https://www.cnblogs.com/freeneng/p/3011684.html
Copyright © 2011-2022 走看看