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

    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.

    思路:这题和求最深深度类似,同样是递归,唯一需要注意一点的是:

          4
        /       这种情况,返回的深度应该是 2 ,而不是1;
      2  
     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 class Solution {
    11     public int minDepth(TreeNode root) {
    12         int lDepth = 0,rDepth = 0;
    13         if (root==null)
    14             return 0;                      //如果一开始传进来空树,则深度为0;
    15         if (root.left!=null&&root.right==null){
    16             lDepth = minDepth(root.left);       //如果出现了左儿子非空,右儿子空,则
    17             return lDepth+1;                         //只递归左儿子就好了
    18         }
    19         else if (root.left==null&&root.right!=null){
    20             rDepth = minDepth(root.right);    //与上同理
    21             return rDepth+1;
    22         }
    23         else{
    24              lDepth = minDepth(root.left);      //否则的话,同时递归左右孩子
    25              rDepth = minDepth(root.right);
    26         }
    27         if (lDepth>rDepth)
    28             lDepth = rDepth;                         //选择左右孩子中深度小的返回;
    29         return lDepth+1;
    30     }
    31 }
    View Code


  • 相关阅读:
    换肤动画
    手风琴动画图
    Ajax传值原理.aspx文档
    三层框架中单表的增删改查
    用ajax传JSON数据
    利用ajax进行post传值,登录QQ和密码代码
    ado.net增删改查及存储过程
    常用的SQL语句
    金融
    写你的简历应该注意什么
  • 原文地址:https://www.cnblogs.com/David-Lin/p/7709458.html
Copyright © 2011-2022 走看看