Skip to content

Instantly share code, notes, and snippets.

@artisanalcode
Created April 28, 2016 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artisanalcode/3d7202ae565a438460f37c6960812dc6 to your computer and use it in GitHub Desktop.
Save artisanalcode/3d7202ae565a438460f37c6960812dc6 to your computer and use it in GitHub Desktop.
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