Java 求二叉树的最小深度
我需要找到二叉树的最小深度。我的代码在此测试用例中失败:Java 求二叉树的最小深度,java,binary-tree,Java,Binary Tree,我需要找到二叉树的最小深度。我的代码在此测试用例中失败:[-9,-3,2,null,4,4,0,-6,null,-5] 给定一棵二叉树,查找其最小深度示例: 给定二叉树[3,9,20,null,null,15,7] 3 / \ 9 20 / \ 15 7 返回其最小深度=2 /** *二叉树节点的定义。 *公共级树节点{ *int-val; *左树突; *特雷诺德右翼; *树节点(intx){val=x;} * } */ 类解决方案{ 公共整数计数(树节
[-9,-3,2,null,4,4,0,-6,null,-5]
给定一棵二叉树,查找其最小深度示例:
给定二叉树[3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回其最小深度=2
/**
*二叉树节点的定义。
*公共级树节点{
*int-val;
*左树突;
*特雷诺德右翼;
*树节点(intx){val=x;}
* }
*/
类解决方案{
公共整数计数(树节点根){
if(root==null){
返回0;
}
返回1+Math.max(count(root.left)、count(root.right));
}
公共int minDepth(树根){
int left=0,right=0;
if(root==null){
返回0;
}
if(root.right==null){
返回1+计数(根.左);
}
if(root.left==null){
返回1+计数(root.right);
}
左=计数(root.left);
右=计数(root.right);
返回1+Math.min(左、右);
}
}
- 输出=4
- 期望值=3
public int minDepth(TreeNode root)
{
if(root == null)
return 0;
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
我认为问题在于使用Math.max而不是Math.min
public int minDepth(TreeNode root)
{
if(root == null)
return 0;
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
助手函数在这里似乎有些过分;将所有逻辑放在一个函数中并向上传递堆栈计数更容易 有3种情况:
- 如果此节点为null,则返回0
- 如果没有子节点,则此节点是叶节点。返回1
- 如果存在左和/或右子节点,则此节点是内部节点。递归计算所有当前子节点的最小深度,并加1以计算当前节点的数量。如果左或右子元素缺失,我们将在计算中忽略它,将其最小值合并到无穷大
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
else if (root.left == null && root.right == null) {
return 1;
}
int left = root.left == null ? Integer.MAX_VALUE : minDepth(root.left);
int right = root.right == null ? Integer.MAX_VALUE : minDepth(root.right);
return Math.min(left, right) + 1;
}
助手函数在这里似乎有些过分;将所有逻辑放在一个函数中并向上传递堆栈计数更容易 有3种情况:
- 如果此节点为null,则返回0
- 如果没有子节点,则此节点是叶节点。返回1
- 如果存在左和/或右子节点,则此节点是内部节点。递归计算所有当前子节点的最小深度,并加1以计算当前节点的数量。如果左或右子元素缺失,我们将在计算中忽略它,将其最小值合并到无穷大
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
else if (root.left == null && root.right == null) {
return 1;
}
int left = root.left == null ? Integer.MAX_VALUE : minDepth(root.left);
int right = root.right == null ? Integer.MAX_VALUE : minDepth(root.right);
return Math.min(left, right) + 1;
}
对于哪个输入
TreeNode
你期望这个输出?@Lutz-Horn我相信他写的4和3的预期输出/输入是指标题中的二叉树。对于哪个输入TreeNode
你期望这个输出?@Lutz-Horn我相信他写的4和3的预期输出/输入是指标题中的二叉树这并不像将最大值切换为最小值那么简单。这只适用于每个节点都有2个子节点的树,否则它会为缺少的子节点提供误判。考虑树<代码> [a,b] < />代码>代码> b>代码> <代码> A<代码>左子。深度应该是2,但这会得到1。它不像将最大值切换为最小值那样简单。这只适用于每个节点都有2个子节点的树,否则它会为缺少的子节点提供假阳性。考虑树<代码> [a,b] < />代码>代码> b>代码> <代码> A<代码>左子。深度应为2,但这等于1。