Java 计算二叉搜索树的平均深度

Java 计算二叉搜索树的平均深度,java,recursion,tree,binary-search-tree,stack-overflow,Java,Recursion,Tree,Binary Search Tree,Stack Overflow,所以我需要计算BST的平均深度,在我的类BST中有这个函数 int totalDepth(Node node, int depth) { if(node == null) { return 0; } return depth // myself + totalDepth(node.left, depth + 1) // my left subtree + tot

所以我需要计算BST的平均深度,在我的类BST中有这个函数

int totalDepth(Node node, int depth) 
{
    if(node == null) 
    {
        return 0;
    }

    return depth                              // myself
     + totalDepth(node.left, depth + 1)   // my left subtree
     + totalDepth(node.right, depth + 1); // my right subtree
}
但当我尝试在main中打印结果时,如下所示:

System.out.println("Average Depth : "+tree.totalDepth(tree.root,0)/10000);
我得到一个堆栈溢出错误


请帮助我

我相信你认为你正在遍历你的二叉树,但是你一直在同一个节点上连续调用
totalDepth
,直到JVM内存耗尽为止


我建议您添加print语句或登录到
totalDepth
方法中,以查看遍历二叉树的深度,或者是否遍历它。我假设
if(node==null)
的计算结果永远不会为true,因此调用堆栈将一直运行,直到内存耗尽。

放入大量调试。从函数开头的部分开始,显示有关当前节点的内容。分离返回表达式,以便可以在使用
node.left
调用之前放置调试打印,然后在使用
node.right
调用之前再次放置调试打印。这应该说明它为什么会螺旋上升。发布显示如何创建
树的代码可能会很有用。树中有多少节点?此外,树的构造是否稳健,即没有循环引用?