Created
April 28, 2016 16:57
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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