计算BST中的节点

时间:2015-08-08 22:11:22

标签: java stack-overflow binary-search-tree

我一直在这一行得到java.lang.StackOverflowError

count += countNodes(current.leftChild);

当我尝试计算BST中的节点总数时。有人可以告诉我为什么我会收到这个错误吗?提前谢谢!

public int countNodes(Node node){
        if(root == null){
            System.out.println("The tree is empty!");
            return -1;
        }
        else{
            int count = 1;
            Node current = root;
            while(current.leftChild != null){
                count += countNodes(current.leftChild);
            }
            while(current.rightChild != null){
                count += countNodes(current.rightChild);
            }
            return count;
        }
    }

3 个答案:

答案 0 :(得分:0)

尝试这个我认为它应该有效

public int countNodes(Node root){
    if(root == null){
        System.out.println("The tree is empty!");
        return 0;
    } 
    else{
        Node current = root;
        int count = 0 
        if(current.leftChild != null){
            count +=  countNodes(current.leftChild)+1;
        }
        if(current.rightChild != null){
            count += countNodes(current.rightChild)+1;
        }
        return count;
    }
}

你从根到叶子的递归。查看循环时使用的代码。在这个递归中你通过递归而不是while循环进入深度的问题。

从左侧树的操作中获取结果并将其添加到右侧的操作中。 递归的停止条件是当根没有孩子时。

何时

  current.rightChild == null && current.leftChild == null

也许我对计数的init感到困惑。检查..

答案 1 :(得分:0)

我发现原始代码存在两个问题。

首先,在查看左右子树时使用while语句。由于您永远不会更改current的值,因此这些循环将永远运行。

第二个问题是您使用名为node的参数,但从不使用它。相反,在方法体内,您引用​​另一个变量root。这就是造成StackOverflowError的原因。

while更改为if应该有助于无限循环,并重命名一些变量,以便您使用函数的参数值来解决堆栈溢出问题。

作为旁注,当节点为空而不是-1时,您可能希望返回零。这样,您可以进行递归调用,而无需检查子节点的空值,更重要的是,当树中的节点为零时,函数会这样说。现在,一个零节点的树看起来像是有-1个节点。

答案 2 :(得分:0)

// ^ _ ^

public int getCount(){
    return getCount(root);
}

public int getCount(BSTNode<T> p){
    if(p == null){
        return 0;
    }
    else{
        int count = 1;
        BSTNode<T> current = p;
        while(current.left != null){
            count += getCount(current.left);
        }
        while(current.right != null){
            count += getCount(current.right);
        }
        return count;
    }
}