Created
June 13, 2021 08:17
-
-
Save antlis/f4b6bf78ecf0e7ec23feb66d7dce8732 to your computer and use it in GitHub Desktop.
This file contains 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
const tree = { | |
value: 1, | |
children: [ | |
{ | |
value: 10, | |
children: [ | |
{ | |
value: 2, | |
}, | |
], | |
}, | |
{ | |
value: 5, | |
}, | |
], | |
}; | |
function treeSum(root) { | |
const reducer = (acc, item) => | |
item.children?.length > 0 ? acc + treeSum(item) : acc + item.value; | |
return root.children.reduce(reducer, root.value); | |
} | |
console.log(treeSum(tree)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment