zoukankan      html  css  js  c++  java
  • [Leetcode] 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.

    Solution:

    第一次提交的错误的代码。

    比如a#b这种左子树为空的树,我直接认为左子树的depth为0了,那当然左子树的depth小,然后parent直接取了0+1。问题在于,某个子树是null的时候,它不是叶子节点啊!这个时候就算没形成一个叶子到root的path,则认为depth为正无穷。

     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         if(root==null)
    13             return 0;
    14         if(root.left==null&&root.right==null)
    15             return 1;
    16         return Math.min(minDepth(root.right), minDepth(root.left))+1;
    17     }
    18 }

    修改过后正确的代码是:

     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         if(root==null)
    13             return 0;
    14         if(root.left==null&&root.right==null)
    15             return 1;
    16         int lDepth=minDepth(root.left);
    17         int rDepth=minDepth(root.right);
    18         if(root.left==null){
    19             lDepth=Integer.MAX_VALUE;
    20         }
    21         if(root.right==null){
    22             rDepth=Integer.MAX_VALUE;
    23         }
    24         return Math.min(rDepth,lDepth )+1;
    25     }
    26 }
  • 相关阅读:
    Mac旧机「焕」新机过程记录
    Swift3.0-字符串和字符
    Swift3.0-基本运算符
    【规范建议】服务端接口返回字段类型与iOS端的解析
    【已解决】iOS11使用MJRefresh上拉加载结束tableView闪动、跳动的问题
    標準メッセージクラス
    BAPI:会計管理(FI&CO)
    BAPI:販売管理(SD)
    BAPI:生産管理(PP)
    BAPI:購買管理(MM)
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4098835.html
Copyright © 2011-2022 走看看