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