【问题标题】:stack overflow binary search tree calculating depth堆栈溢出二叉搜索树计算深度
【发布时间】:2017-04-10 17:25:25
【问题描述】:

我正在尝试计算二叉搜索树中键的深度,但出现堆栈溢出错误,我不知道为什么。这是我当前的代码。

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新手,所以请原谅这个问题的初学者水平

【问题讨论】:

  • 你知道你没有使用参数“x”吗?
  • 你能展示你的比较器吗?
  • 如果给定的密钥不存在,算法返回 -1 失败

标签: java recursion tree polymorphism binary-search-tree


【解决方案1】:

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

这是因为,您总是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。为了克服这个问题,只需插入一个条件来检查当前的tree 是否为空,如果我们没有找到我们的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; 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-24
    • 2021-10-16
    • 2010-12-24
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多