计算二叉树的正确节点

时间:2019-07-08 22:56:37

标签: 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 {
    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;
     }

对我来说似乎更合法。可能是第一个版本失败的情况吗?

谢谢

3 个答案:

答案 0 :(得分: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 :(得分:-1)

您的第一个代码将重新运行2,而不会返回1 递归调用

返回1个或另一个更深层次的调用,直到root.right == null

将根据您的结构获得2个回报 您编码的树不同于您绘制的树

答案 2 :(得分:-1)

假设您无法调试, 如果参数“ NodeT root”为空,则只会返回0。

我想你要

public int countRight(NodeT root, int currentDepth){
         if (root==null
            || root.right == null) // missing this comparison
             return currentDepth;
         else{
             return countRight(root.right, currentDepth++);
         }
     } 

Tree tree=new Tree();
NodeT root=tree.createTree();
System.out.println(tree.countRight(root), 0) // 0 is the begin
相关问题