LeetCode - 111. Minimum Depth of Binary Tree

以前做过一道Maximum Depth of Binary Tree的题目,思想是使用divide and conquer的思想和recursion的方式,这次一开始的时候仍然按照那个方法去做,结果失败了。问题出在哪儿呢?考虑下面的情况:


这时候如果按照原来那种写法的话,这个树的最低高度应该是2,但是Math.min(1, 0) + 1得到的结果为1,所以是不对的,要更加全面的考虑出现的情况。那么为什么原来maximum depth的时候这样写可以呢?因为Math,max(1, 0) + 1得到的结果是2,把root.left == 0和root.right == 0的情况包括了,更全面的代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        if(root.left == null && root.right == null) return 1;
        
        if(root.left == null) return minDepth(root.right) + 1;
        else if(root.right == null) return minDepth(root.left) + 1;
        else return Math.min(minDepth(root.right), minDepth(root.left)) + 1;
    }
}


试了一下,如果把这个代码中的Math.min替换成Math.max的话同样可以得到maximum depth。

知识点:

1. 注意掌握二叉树最大高度和最低高度的写法,可以记录下来

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值