Recursive search for a node in non-binary tree

前端 未结 2 898
死守一世寂寞
死守一世寂寞 2020-12-29 10:59

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.

2条回答
  •  独厮守ぢ
    2020-12-29 11:55

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

提交回复
热议问题