java - 堆栈溢出二叉搜索树计算深度

标签 java recursion tree polymorphism binary-search-tree

我正在尝试计算二叉搜索树中键的深度,但出现堆栈溢出错误,但我不确定原因。这是我当前的代码。

private int calcDepth( Tree<K, V> x, K keyIn, int currentLevel){ 
  //BASE CASE  
  if (this.key.compareTo(keyIn) == 0) return currentLevel; 

  if (this.key.compareTo(keyIn) < 0){ 
     return calcDepth(this.left, keyIn, currentLevel+1);  
  }

  if (this.key.compareTo(keyIn) > 0){ 
     return calcDepth(this.right, keyIn, currentLevel + 1); 
  }

  return -1; 
}

这是我的算法

//ALGORITHIM 
//1. if the current key is equal to the parameter key 
//   return the currentLevel 
//2. if the current key is less than the parameter key 
//   go left and increment the level 
//3. if the current key is greater than the paramete key 
//   go right  and increment the level 
//4. if none of these cases are met (key is not in tree
//   return -1 

我是java新手,所以请原谅这个问题的初学者水平

最佳答案

I am getting a stack overflow error and I'm not sure why

这是因为,您始终this.leftthis.right 作为参数传递给该方法calcDepth 始终相同。此外,this.key 始终相同,因此本质上您始终比较两个键(this.keykeyIn),而不实际遍历树。即它应该是:

if (x.key.compareTo(keyIn) == 0) 

然后当你调用时:

calcDepth(x.left, keyIn, currentLevel+1); 

calcDepth(x.right, keyIn, currentLevel + 1);

x 是每次调用该方法时的不同实例。

看来您没有对参数 x 执行任何操作。您应该使用 x.key (其中 x表示树的当前实例)。

现在,x.leftx.right 在每次调用该方法时都会有所不同,因此本质上我们正在缩小问题范围并达到基本情况,因此该方法将能够返回到调用方法并最终结束,而不会出现 StackOverflow 异常。

最后但并非最不重要的一点是,您的代码中存在一个额外的错误,如果给定的 key 不存在,算法将无法返回 -1。要解决这个问题,只需插入一个条件来检查当前的是否为空,如果我们没有找到key,我们可以简单地返回 -1

注意 - 这也将防止出现 NullPointerException 的可能性。

private int calcDepth( Tree<K, V> x, K keyIn, int currentLevel){ 

  if(x == null) return -1; // key doesnt exist if this is true

  if (x.key.compareTo(keyIn) == 0) return currentLevel;  //BASE CASE  

  if (x.key.compareTo(keyIn) < 0){   // check left tree
      return calcDepth(x.left, keyIn, currentLevel+1);  
  }

  if (x.key.compareTo(keyIn) > 0){  // check right tree
      return calcDepth(x.right, keyIn, currentLevel + 1); 
  }

  return -1; 
}

关于java - 堆栈溢出二叉搜索树计算深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43329374/

相关文章:

java - 将代码移入包后出现 UnsatisfiedLinkError

c++ - 在递归函数上使用 unordered_map unordered_set 的段错误

python - XML 子元素中的变量

algorithm - 如何从给定的列表中有效地构建 B+ 树?

python - 在 bash 中可视化树,如 unix "tree"的输出

java - Eclipse插件开发: custom profiler (JDT )

java - 框架和按钮

java - 在 Java 中导入特定包或带有通配符的整棵树更好吗?

ruby - 什么是递归,它是如何工作的?

javascript - 为什么 += 在递归中不起作用?