Created
August 29, 2018 23:39
-
-
Save JaosnHsieh/fd8eea70d80cddb5572482a4fcabe9db to your computer and use it in GitHub Desktop.
Recursive sum leaf nodes values bottom up to parrent node.
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
| var dumpHead = { | |
| label: "root", | |
| value: 0, | |
| children: [ | |
| { | |
| label: "a", | |
| value: 0, | |
| children: [ | |
| { | |
| label: "a-2-1", | |
| value: 0, | |
| children: [ | |
| { | |
| label: "a-3-1", | |
| value: 3 | |
| } | |
| ] | |
| }, | |
| { | |
| label: "a-2-2", | |
| value: 0, | |
| children: [ | |
| { | |
| label: "a-3-2", | |
| value: 2 | |
| }, | |
| { | |
| label: "a-3-3", | |
| value: 3 | |
| }, | |
| { | |
| label: "a-3-4", | |
| value: 10 | |
| } | |
| ] | |
| } | |
| ] | |
| }, | |
| { | |
| label: "b", | |
| value: 0, | |
| children: [ | |
| { | |
| label: "b-2-1", | |
| value: 0, | |
| children: [ | |
| { | |
| label: "b-3-1", | |
| value: 5 | |
| } | |
| ] | |
| }, | |
| { | |
| label: "b-2-2", | |
| value: 0, | |
| children: [ | |
| { | |
| label: "b-3-2", | |
| value: 2 | |
| }, | |
| { | |
| label: "b-3-3", | |
| value: 4 | |
| } | |
| ] | |
| } | |
| ] | |
| }, | |
| { | |
| label: "c", | |
| value: 0, | |
| children: [ | |
| { | |
| label: "c-2-1", | |
| value: 0, | |
| children: [ | |
| { | |
| label: "c-3-1", | |
| value: 8 | |
| } | |
| ] | |
| }, | |
| { | |
| label: "c-2-2", | |
| value: 0, | |
| children: [ | |
| { | |
| label: "c-3-2", | |
| value: 9 | |
| }, | |
| { | |
| label: "c-3-3", | |
| value: 10 | |
| } | |
| ] | |
| } | |
| ] | |
| } | |
| ] | |
| }; | |
| function traverse(node) { | |
| if (node.children === undefined) return node.value; | |
| var total = 0; | |
| for (var i = 0; i != node.children.length; ++i) { | |
| total += traverse(node.children[i]); | |
| } | |
| node.value = total; | |
| return node.value; | |
| } | |
| traverse(dumpHead); | |
| console.log(JSON.stringify(dumpHead, null, 2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment