我怎样才能改变这段代码,使我只有getKey?
private void searchForK(V value , DictionaryNode<K,V> node){
if(node != null){
if(((Comparable<V>)value).compareTo(node.value) == 0) {
obtainKey = node.key;
return;
}
searchForK(value,node.lChild); //recursive since we have to simply look
searchForK(value,node.rChild);//through each child which is itself another searchforK
}
}
public K getKey(V value) {
searchForK(value,rNode);
return obtainKey;
}//end getKey
如何将上述代码更改为getKey的函数?我对递归感到困惑。我想摆脱searchForK函数,并让getKey具有与searchForK相同的功能。我怎样才能改变这段代码,使我只有getKey?
这是我在改变两个功能的尝试:
public K getKey(V value) {
// private void searchForK(V value , DictionaryNode<K,V> node){
if(rNode != null){
if(((Comparable<V>)value).compareTo(rNode.value) == 0) {
obtainKey = rNode.key;
return (K) obtainKey;
}
rNode = rNode.lChild;
getKey(value);
rNode = rNode.rChild;
getKey(value);
}
return null;
它不行为相同的方式,虽然,我究竟做错了什么?
这些都是我的全局变量:
public class BinarySearchTree<K,V> implements DictionaryADT<K,V> {
/* data fields */
/* Node Variables */
public DictionaryNode<K,V> rNode; //Root Node
public DictionaryNode<K,V> pNode; //Parent Node
K obtainKey;
我是否应该更换rNode是CURNODE在我的情况?
private DictionaryNode<K,V> curNode = rNode;
public K getKey(V value) {
if (curNode != null) {
int c = ((Comparable<V>)curNode.value).compareTo(value);
if (c == 0) {
K key = curNode.key;
curNode = rNode; // reset curNode
return key;
}
else if (c < 0 && curNode.lChild != null) {
curNode = curNode.lChild;
return getKey(value);
}
else if (curNode.rChild != null) {
curNode = curNode.rChild;
return getKey(value);
}
}
curNode = rNode; // reset curNode
return null;
}
为什么你的DictionaryNode不在函数中? – TwilightSparkleTheGeek
啊我看你现在在做什么,一秒钟 – robbmj
你呢?你怎么知道我在做什么? – TwilightSparkleTheGeek
我还是个新手,当谈到递归。这对我来说有点困难。 – TwilightSparkleTheGeek
您将不得不使用两个引用来跟踪您当前正在递归的位置,因为您无法通过每次递归调用将引用传递给节点。你在搜索什么类型的数据结构? – robbmj
我正在搜索二进制搜索树。这是杀了我的男人。递归是。谢谢你的协助。我还有另一部分需要帮助。你能和我在一起吗?我是计算机科学系的学生,本科生。 – TwilightSparkleTheGeek