Recursive search for a node in non-binary tree

风流意气都作罢 提交于 2019-12-18 02:47:57

问题


I want to search for an item in non-binary tree (any node can have n - children) and exit from recursion immediately. The node in question can be any node, not only leafs.

This is my code but i don't get complete search.

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 contains :

ArrayList mChildren ; (it's children)
and data object.


回答1:


You shouldn't exit after exploring the first child. You don't need the if statement in front of the for loop.

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:


In your code if recursiveSearch(gi, children[i]) returned null then i+1 not searched, modify:

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;
 }


来源:https://stackoverflow.com/questions/8617790/recursive-search-for-a-node-in-non-binary-tree

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!