【发布时间】: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