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
- LeetCode 111. Minimum Depth of Binary Tree
- [LeetCode]111.Minimum Depth of Binary Tree
- 【LeetCode】111.Minimum Depth of Binary Tree
- [Leetcode] 111. Minimum Depth of Binary Tree
- [leetcode] 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree LeetCode
- 【LeetCode】111. Minimum Depth of Binary Tree
- LeetCode *** 111. Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- leetcode-111. Minimum Depth of Binary Tree
- LeetCode-111.Minimum Depth of Binary Tree
- LeetCode 111.Minimum Depth of Binary Tree
- Leetcode 111. Minimum Depth of Binary Tree
- [leetcode]111.Minimum Depth of Binary Tree
- 111.[Leetcode]Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- 【leetcode】111. Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- HTTP状态码大全
- apache服务器外网不能访问的问题
- webRTC 音频类别
- NSURLSession 简介
- 《C++语言基础》网络课程主页
- LeetCode - 111. Minimum Depth of Binary Tree
- 文件不可超过2m
- 计蒜之道复赛A题 百度地图的实时路况(分治+floyd)
- ssh初步整合
- TCP/IP协议栈与数据包封装
- day——05 迭代器,生成器
- Redis need tcl 8.5 or newer
- [2016 indeed笔试题] Tables and Pieces
- 求一个圆的面积及判断一个点是否在圆内