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 }
  • 相关阅读:
    软件测试学习-计算机基础知识
    《剑指offer》— JavaScript(4)重建二叉树
    《剑指offer》— JavaScript(3)从尾到头打印链表
    《剑指offer》— JavaScript(1)二维数组中的查找
    《剑指offer》— JavaScript(2)替换空格
    React学习笔记
    dislpay:flex布局
    JavaScript异步编程的方法
    test of CMSoft
    全局对象和全局函数
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4098835.html
Copyright © 2011-2022 走看看