下面是实现二叉搜索树的代码:
public class BST<T extends Comparable<T>> {
BSTNode<T> root;
public T search(T target)
{
//loop to go through nodes and determine which routes to make
BSTNode<T> tmp = root;
while(tmp != null)
{
//c can have 3 values
//0 = target found
//(negative) = go left, target is smaller
//(positive) = go left, target is greater than current position
int c = target.compareTo(tmp.data);
if(c==0)
{
return tmp.data;
}
else if(c<0)
{
tmp = tmp.left;
}
else
{
tmp = tmp.right;
}
}
return null;
}
/*
* Need a helper method
*/
public T recSearch(T target)
{
return recSearch(target, root);
}
//helper method for recSearch()
private T recSearch(T target, BSTNode<T> root)
{
//Base case
if(root == null)
return null;
int c = target.compareTo(root.data);
if(c == 0)
return root.data;
else if(c<0)
return recSearch(target, root.left);
else
return recSearch(target, root.right);
}
为什么我需要递归辅助方法?为什么不能只使用“this.root”来执行正在发生的递归过程?此外,如果搞砸正在调用此方法的对象的根属性是一个问题,那么辅助方法如何防止这种情况发生?它是否只是创建了一个与 this.root 属性分开的指针,因此不会弄乱正在调用该方法的对象的根属性?
抱歉,如果这个问题看起来不直接,但如果有人能告诉我幕后究竟发生了什么,我将不胜感激。