堆栈溢出二进制搜索树计算深度

时间:2017-04-10 17:25:25

标签: 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的新手,请原谅问题的初学者水平

1 个答案:

答案 0 :(得分:3)

  

我收到了堆栈溢出错误,我不知道为什么

这是因为,您总是this.leftthis.right作为方法calcDepth的参数传递给<{1}}强>总是一样。此外,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异常结束。

最后但并非最不重要的是,代码中还有一个错误,如果给定的-1不存在,算法将无法返回key。要解决此问题,只需插入一个条件,检查当前tree是否为空,如果我们没有找到key,我们就可以返回{{1} }}。

注意 - 这也可以防止出现NullPointerException。

-1
相关问题