LeetCode - 111. Minimum Depth of Binary Tree

来源:互联网 发布:淘宝卖家代销怎么发货 编辑:程序博客网 时间:2024/06/05 06:40

以前做过一道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