【发布时间】:2023-03-25 15:15:01
【问题描述】:
我想统计一棵二叉树的正确节点,例如下面这个:
15
/
10
\
14
所以我做了以下程序:
public class NodeT {
int elem;
NodeT left;
NodeT right;
public NodeT(int elem){
this.elem=elem;
left=null;
right=null;
}
}
public class Tree {
public NodeT createTree(){
NodeT root=new NodeT(15);
NodeT n1=new NodeT(10);
NodeT n4=new NodeT(14);
root.left=n1;
n1.right=n4;
return root;
}
public int countRight(NodeT root){
if (root==null) return 0; //version 1
else{
return 1+countRight(root.right);
}
}
我通过以下方式调用我的主程序:
Tree tree=new Tree();
NodeT root=tree.createTree();
System.out.println(tree.countRight(root))
此代码打印 1 作为正确答案,但我不明白为什么会发生这种情况。对于我看到的 15 的右分支等于 null,因此对递归函数 countRight() 的调用应该返回 0 并打印一个不正确的答案。
我见过其他解决方案,我发现为了计算所有节点,他们使用如下解决方案:
static int n;
public int countRight(NodeT root){ //version 2
if (root==null) return 0;
if (root.left!=null){
n=countRight(root.left);
}
if (root.right!=null){
n++;
n=countRight(root.right);
}
return n;
}
这对我来说似乎更合法。会不会是第一个版本失败的情况?
谢谢
【问题讨论】:
-
你没有添加左子树的右节点
-
那棵树你应该得到什么答案?
-
您返回
1+countRight(root.right)而不对root.right进行空检查。这意味着即使正确的节点为空,您仍要为其添加一个。此外,您永远不会像皇家幽灵所指出的那样检查树的左侧。为此,您还需要在退货中添加+countRight(root.left)。
标签: java