Search code examples
tree-structuretree-search

Tree search function


Any node can have any number of children. To search this tree i wrote something like this

function Search(key, nodes){

 for (var i = 0; i < nodes.length; i++) {


        if (nodes[i].key == key) {
            return nodes[i];
        }



        if (nodes[i].hasOwnProperty('children')) {
            return this.Search(key, nodes[i].children);
        }


    }

which doesn't quite work...any input?


Solution

  • You only recursively search the first node that has children.

    You should rewrite that last conditional to something like this:

    if (nodes[i].hasOwnProperty('children')) {
        var node = this.Search(key, nodes[i].children);
        if(node != null)
            return node;
    }
    

    You also need to add a case for if the node is not found - for example, a return null at the very bottom of the function.