Java 计算二叉树的右节点数
我想计算二叉树的正确节点数,例如以下节点:Java 计算二叉树的右节点数,java,Java,我想计算二叉树的正确节点数,例如以下节点: 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
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;
}
这对我来说更合法。是否会出现第一个版本失败的情况
谢谢您的第一个代码将重新运行2,它不会返回1 递归调用 返回1+另一个更深的调用,直到root.right==null 根据您的结构,将导致2次退货
您编码的树与您绘制的树不同。这样的方法不应使用静态字段,也不应使用任何字段 任务是计算右节点的数量,这实际上意味着计算
right
不为空的节点数量。您并不是在计算节点,而是对节点的引用
这还意味着您必须扫描所有节点,这意味着该方法必须同时遍历左侧和右侧
最后,根据定义,根节点不是正确的节点
public int countRight(NodeT node) {
if (node == null)
return 0;
if (node.right == null)
return countRight(node.left);
return 1 + countRight(node.left) + countRight(node.right);
}
您没有添加左子树的右节点该树的答案是什么?返回
1+countRight(root.right)
,而不对root.right
进行空检查。这意味着即使右节点为null,也可以为其添加一个。此外,你从来没有检查过左边的树指出的皇家幽灵。要做到这一点,您还需要在返回中添加一个+countRight(root.left)
。“它不可能返回1”好吧,问题说“此代码打印1”,所以它显然可能发生,因为它计算根节点,就是这样,因为“在root.right==null之前的另一个更深的调用”立即为真(提示:root.right=null)。这将返回2它显然不是1 go它1不等于2 ok,绘图不代表代码它完全不同的结构你明白吗?createTree()
方法创建了绘图中显示的树。有3个节点,值分别为15、10和14,因此我们将它们称为n15、n10和n14。当您使用根(n15)调用第一个版本的countRight()
时,它将执行1+countRight(n15.right)
。由于n15.right
为空,因此使用do返回0的调用
,这意味着第一个调用最终为返回1+0
,因此最终结果为1。谢谢@Andreas,你能给我一个版本1失败的例子吗?因为当我运行它时,它似乎打印了正确的answer@Little当然,将root.left=n1
更改为root.right=n1
。这将使节点15成为根节点,节点10和14成为右节点,因此有2个右节点,但代码返回3。--或者,将n1.right=n4
更改为n1.left=n4
。这将使节点10和14成为左节点,因此0个右节点,但代码返回1。