java - 我该如何更改这段代码,以便我只有 getKey?

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

最佳答案

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;

关于java - 我该如何更改这段代码,以便我只有 getKey?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20483732/

相关文章:

java - 当线程调用 wait 时,它会释放锁而不是竞争条件

java - 尝试获取泛型类型类时出现 ClassCastException

java - 当我在 android 中发送 post 请求时,它什么也不返回。当我向服务器发送发布请求时,它会显示写入内容

java - 使用 Java 将 docx/ODT 转换为图像

java - 如何重置以前单击的按钮的颜色?

java - 集成 Java Webapp + drools + Guvnor 如何以及是否值得?

java - 如何将以下字符串转换为日期对象?

java - Cocoon 2.1.x 到 2.2.0 迁移指南

java - 为什么每次继续 while 循环时我的变量都会被重置?

java - 从应用注册中列出 Azure 存储帐户容器时,受众验证失败