0

I have One Root Node "A" in a tree view and "A" node may have any number of child node and so on. I have to search a node in this tree and want to know the level of searched node in given tree. need a logical implementation in java/Java script using Collection framework and core java or JQuery.

bellow is the JSON data in which i need search.

var data=[{"id":"a","children":[{"id":"b","children":[{"id":"c","children":[{"id":"f","children":[{"id":"h"}]}]},{"id":"d"},{"id":"e"}]}]}]

here in above JSON if i want to get object of id f, I am using method findNode(data,"f") that will give me object of node f, but i also want level of node f which is level 3, how could i get it. and suggest me another way to search node that will increase search performance, this approach is very slow because recursively i have to hit the database to get next record in java and in java script the amount of data/JSON will become large that may cause crash the browser.

function findNode(node, nodeId) {
    var childrenLen, found;
    if (node.id === nodeId) {
        return node;
    } else if (node.children) {
        childrenLen = node.children.length;
        while(childrenLen--) {
            found = findNode(node.children[childrenLen], nodeId);
            if(found) {
                return found;
            }
        }
    }
}
  • Use recursion to search the tree. This way you get the level and whatever you are looking for. And then post the code regarding what have you tried? – Jaskaranbir Singh Jul 29 '16 at 13:58
  • For every node j { if node i'm looking for ==> return level (can be passed via argument), else ==> recursive call to your search function, but with node j and with level + 1 }. You can use the value -1 to indicate that the node was not found in the searched sub-tree. – MrKickkiller Jul 29 '16 at 14:04
  • Without any of your code to work with, based on your question alone (which hints to homework assignment requirements) checkout some other Q&A's on this site: [How to get depth of a node in one recursive search in non-binary tree](http://stackoverflow.com/q/21694887/1248974), [How to calculate the depth of a binary search tree](http://stackoverflow.com/questions/1876255/how-to-calculate-the-depth-of-a-binary-search-tree). Good luck! – chickity china chinese chicken Jul 29 '16 at 18:41

0 Answers0