【问题标题】:Recursive search for a node in non-binary tree递归搜索非二叉树中的节点
【发布时间】:2012-01-26 21:58:57
【问题描述】:

我想在非二叉树中搜索一个项目(任何节点都可以有 n 个子节点)并立即退出递归。有问题的节点可以是任何节点,而不仅仅是叶子。

这是我的代码,但我没有得到完整的搜索。

private nNode recursiveSearch(data gi,nNode node){
        if (node.getdata()==gi)
            return node;
        nNode[] children = node.getChildren(); 
        if (children.length>0)
        for (int i = 0; i < children.length; i++) {         
            return recursiveSearch(gi, children[i]);
        }
        return null;
 }

nNode 包含:

ArrayList mChildren ;(是孩子)
和数据对象。

【问题讨论】:

  • 你的nNode是什么样的?

标签: java search tree


【解决方案1】:

您不应该在探索完第一个孩子后退出。您不需要在 for 循环前面使用 if 语句。

private nNode recursiveSearch(data gi,nNode node){
    if (node.getdata()==gi)
        return node;
    nNode[] children = node.getChildren(); 
    nNode res = null;
    for (int i = 0; res == null && i < children.length; i++) {         
        res = recursiveSearch(gi, children[i]);
    }
    return res;
 }

【讨论】:

    【解决方案2】:

    在您的代码中,如果 recursiveSearch(gi, children[i]) 返回 null 则 i+1 未搜索,请修改:

    private nNode recursiveSearch(data gi,nNode node){
            if (node.getdata()==gi)
                return node;
            nNode[] children = node.getChildren(); 
            nNode temp;
            if (children.length>0)
            for (int i = 0; i < children.length; i++) {         
                temp = recursiveSearch(gi, children[i]);
                if(temp!=null)
                    return temp;
            }
            return null;
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-19
      • 2014-05-10
      • 2013-03-10
      • 2014-01-02
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多