Withtaker
Withtaker

Reputation: 1884

Search method for tree with multiple children per node

I created the following Method to search for a certain ParentReference Id in a Tree that is unsorted and where every node can have any number of children. If the given parentRef matches the Node's parentRef, the Node should be returned.

public static <T>Node<T> search(Node<T> node, int parentRef) {
    if(node.getParentRef() == parentRef){
        return node;
    }
    if(node.getChildren()!= null){
        for(int i = 0; i < node.getChildren().size(); i++){
            if(node.getChildren().get(i).parentRef == parentRef){
                return node;
            }
            else {
                search(node.getChildren().get(i), parentRef);
            }
        }
    }
    return null;
}

However, it does not work and always returns null but I don't know why. Can anybody explain what I am doing wrong?

Upvotes: 1

Views: 921

Answers (1)

Mureinik
Mureinik

Reputation: 311308

In the else branch, you call search recursively, but don't return its value, so it is lost. You should check if it's not null, and if so, return it:

else {
    Node<T> result = search(node.getChildren().get(i), parentRef);
    if (result != null) {
        return result;
    }
}

Upvotes: 2

Related Questions