【发布时间】:2021-05-27 11:24:27
【问题描述】:
尝试解决这个 LC Easy:https://leetcode.com/problems/minimum-depth-of-binary-tree/
这是找到一棵树的最小深度(最短路径上的节点数)。
我能够创建一个“findheight”函数,它可以给我一棵树的高度。
我的逻辑是使用 findheight 找到根节点的两个子树(左和右)的高度,然后返回两个高度之间的最小值。
class Solution {
public int minDepth(TreeNode root) {
if(root == null){return 0;}
int left = findHeight(root.left);
int right = findHeight(root.right);
//unbalanced tree, only one subtree
if(left == 0 || right == 0){
return Math.max(left,right) + 1;
}
return Math.min(left,right) + 1 ;
}
public int findHeight(TreeNode root){
if(root == null){return 0;}
int left = findHeight(root.left);
int right = findHeight(root.right);
return Math.max(left,right) + 1;
}
}
它不会通过测试用例:
[-9,-3,2,null,4,4,0,-6,null,-5]
或者:
Output:
4
Expected:
3
我现在的想法是,当我使用“findHeight”时,我将返回每个左右子树的“最大”高度。在这个测试用例中,我应该返回最小高度。
我在另一次迭代中将代码更改为“Math.min”,但这也不起作用。
任何想法或理论为什么?如此迷茫!!我应该完全放弃这种方法吗?
【问题讨论】:
-
在帖子中直接描述您的代码、问题以及您想要实现的目标,而不是引用外部链接
-
对不起,我是 StackOverflow 的新手。我已经编辑了我的问题以进一步解释我的思考过程。
-
@buddybuddybuddybuddy,
findHeight当前找到最大高度。我添加了一个有效的答案。
标签: java binary-search-tree depth-first-search breadth-first-search depth