我怎么能改变这段代码,以便我只有getKey?

时间:2013-12-10 00:30:03

标签: java

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相同的功能。

以下是我尝试更改这两个功能的方法:

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吗?

1 个答案:

答案 0 :(得分:1)

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;

}