Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A function will traverse a tree passed as an argument. The function will add the number values contained on each node when available.
// Will traverse a tree passed as an argument. The function will add the number values contained on each node when available.
function traverseAndAdd(tree) {
// Init var to contain sum of values
var sum = 0;
// Function will traverse nodes
var recursiveCrawl = function (branch) {
for (i in branch) {
// If node contains children use recursion to reach children
if ( typeof branch[i] == "object" ) {
recursiveCrawl (branch[i]);
}
// Child node has no children, if is a number, add it to the total sum
else if (typeof branch[i] == "number"){
// Add value to total sum
sum = sum + branch[i];
}
}
}
// Call function
recursiveCrawl(tree);
// Return total sum of nodes' values
return sum;
}
// Use to test function. JSON object, tree structure.
var tree = {
"id": 100,
"children": [
{
"id": 110,
"children": [
{
"id": 111
},
{
"id": 112
}
]
},
{
"id": 120,
"children": [
{
"id": 121
},
{
"id": 122
}
]
},
{
"id": 130,
"children": [
{
"id": 131
},
{
"id": 132
}
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.