Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive search for a node in non-binary tree

Tags:

java

search

tree

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.

like image 311
omrid Avatar asked Dec 23 '11 15:12

omrid


1 Answers

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;
 }
like image 194
Sergey Kalinichenko Avatar answered Sep 21 '22 09:09

Sergey Kalinichenko