【问题标题】:Searching for a specific node of an unsorted tree搜索未排序树的特定节点
【发布时间】:2015-06-16 16:44:15
【问题描述】:

一般的思路是使用递归回溯(BinaryNode,数据为Character)遍历一棵树,找到一个特定的char。该方法将输出从根到数据为指定字符的节点的路径。向左移动意味着路径为 0,向右移动意味着路径为 1。因此,例如,到最上面的根节点的路径是一个空字符串,到左子节点的路径是 0(而 1正确的孩子)。

到目前为止,我有一个递归 void 方法,其基本情况是如果找到匹配项,则方法结束。否则,如果有左孩子,我会再次调用该方法,然后检查和/或调用右孩子。最后一部分是当前根是叶节点,我会修改存储路径以消除最近添加的 0 或 1,然后返回到之前的递归调用。这是我目前所拥有的

//method head
if(c==root.getData()) return;

if(root.hasLeftChild()) //call method with left child as root, and a 0 added to path

//same for right child, only add a 1 instead of a 0

//if leaf node aka neither left or right child, path will now be a substring from 0 to path.length()-1

感谢您的帮助!

【问题讨论】:

    标签: java recursion tree backtracking


    【解决方案1】:
    recurAndFind(String str, Node x, char c){
    if(x== null);
    if(x.getChar() == c)
       return str;
    else if(x.hasLeft())
        recurAndFind("0"+str,x.left,c);
    else if(x.hasright())
         recurAndFind("1"+str,x.right,c);
    }
    

    这将做你想做的事情,但是一旦你收到字符串,你必须检查内容是什么,并做出相应的决定。您需要向它发送一个空字符串。

    【讨论】:

    • 非常感谢!像你这样的人真棒!
    【解决方案2】:

    注意:由于没有提供 BinaryNode 的实现,我只是使用它应该提供的一些基本方法。

    public String getPath(char c , BinaryNode<Character> node){
         if(node.getData() == c)//matching node found
              return "";
    
         if(node.right() != null){//check if right child is parent of match
              String tmp = getPath(c , node);
              if(tmp != null)//match found -> complete path from this node
                   return "1" + tmp;
         }
         if(node.left() != null){//check if left child is parent of match
              String tmp = getPath(c , node);
              if(tmp != null)
                   return "0" + tmp;
         }
    
         //c is no content of the tree with node as root -> return null
         return null;
    }
    

    此代码合二为一。当它深入到树中时,它会搜索匹配的节点,当算法回到树的根部时,会向后生成路径(结果顺序正确)。

    【讨论】:

    • 非常感谢!像你这样的人真棒!
    猜你喜欢
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    相关资源
    最近更新 更多