I am writing Javascript code. I have a JSON object that looks like this (spacing changed for readability):
var myNodes = [
{
id: 4,
children: [
{
id: 1,
children: [
]
},
{
id: 3,
children: [
]
}
]
},
{
id: 2,
children: [
]
},
{
id: 6,
children: [
{
id: 5,
children: [
]
}
]
}
]
Each node id in this data structure is unique. However, other than this, there are no fixed or known relationships between ID numbers in general. And the number of children at each level is not limited.
If I want to find this tree and return node with id == 6. How can I do this? I wrote the following code, however, after it encounters the first node leaf, the whole algorithm returns false, which is clearly wrong. I'm just trying to do a basic depth search. But I do not want to add additional fields to this data and “mark” the nodes, as I saw in some DFS implementations on the Internet.
myClass.prototype.nodeSearch = function nodeSearch(treeNodes, searchID){
for (var nodeIdx = 0; nodeIdx <= treeNodes.length-1; nodeIdx++)
{
console.log("Comparing treeNodes element with ID==" + treeNodes[nodeIdx].id + " to SearchID==" + searchID);
if (treeNodes[nodeIdx].id == searchID)
{
console.log("Match!");
return treeNodes[nodeIdx];
}
else
{
console.log("No Match! Trying " + treeNodes[nodeIdx].children.length + " Children of Node ID#" + treeNodes[nodeIdx].id);
return this.nodeSearch(treeNodes[nodeIdx].children, searchID);
}
}
console.log("Done trying " + treeNodes.length + " children. Returning False");
return false;
};