Java 正在查找二叉树的最小高度…代码缺少1个小编辑以通过所有测试用例
我想找出一棵树的最小高度。我修改了查找树的最大高度的原始算法(但这次只使用Math.min而不是Math.max) 它能够传递一个普通树,并且Integer.MAX_值用于的测试用例Java 正在查找二叉树的最小高度…代码缺少1个小编辑以通过所有测试用例,java,tree,binary-tree,binary-search-tree,Java,Tree,Binary Tree,Binary Search Tree,我想找出一棵树的最小高度。我修改了查找树的最大高度的原始算法(但这次只使用Math.min而不是Math.max) 它能够传递一个普通树,并且Integer.MAX_值用于的测试用例 2 \ 3 \ 4 \ 5 但是,该代码将无法通过简单地具有空输入“[]”的测试用例 我能对这段代码做些修改吗?我挠头,想知道我是否应该删除它,从头开始。不过我觉得很亲近 LC问题:代码中的问题是,例如,当树倾斜时,它将返回到目前为止所遍历的子树的最小深度值。 如果考虑
2
\
3
\
4
\
5
但是,该代码将无法通过简单地具有空输入“[]”的测试用例
我能对这段代码做些修改吗?我挠头,想知道我是否应该删除它,从头开始。不过我觉得很亲近
LC问题:代码中的问题是,例如,当树倾斜时,它将返回到目前为止所遍历的子树的最小深度值。 如果考虑以下树:
2
\
3
\
4
\
5
它应该返回-2147483648
仔细检查根的左右子树,即2
left subtree depth value: Integer.MAX_VALUE (+1) = -2147483648
right subtree depth value: 4 (+1) = 5
现在检查下一个元素,即3
minimum value found so far: -2147483648
right subtree depth value: 3 (+1) = 4
现在检查下一个元素,即4
minimum value found so far: -2147483648
right subtree depth value: 2 (+1) = 3
等等。。最后,我们将得出迄今为止我们找到的最小数量,即-2147483648
,或者在2147483647
的情况下,当树为空或null
时
您需要更改逻辑,在这种情况下,最大深度节点应采用最小深度值:
我为您编写了一个解决方案,请检查它是否有效:
int min = Integer.MAX_VALUE;
public int minDepth(TreeNode root) {
if(root == null){
return 0; /* return 0 when the tree is empty */
}
/* visit each node in DFS manner, and found maximum depth-ed node possible */
minDepth(root, 0);
return min+1;
}
private void minDepth(TreeNode root, int count){
if(root == null){
return;
}else if(root.left == null && root.right == null){
/* replace the minimum value with maximum-depth node counter */
if(min > count){
min = count;
}
}else{
count += 1;
minDepth(root.left, count);
minDepth(root.right, count);
}
int min = Integer.MAX_VALUE;
public int minDepth(TreeNode root) {
if(root == null){
return 0; /* return 0 when the tree is empty */
}
/* visit each node in DFS manner, and found maximum depth-ed node possible */
minDepth(root, 0);
return min+1;
}
private void minDepth(TreeNode root, int count){
if(root == null){
return;
}else if(root.left == null && root.right == null){
/* replace the minimum value with maximum-depth node counter */
if(min > count){
min = count;
}
}else{
count += 1;
minDepth(root.left, count);
minDepth(root.right, count);
}