Skip to content

Instantly share code, notes, and snippets.

@antlis
Created June 13, 2021 08:17
Show Gist options
  • Save antlis/f4b6bf78ecf0e7ec23feb66d7dce8732 to your computer and use it in GitHub Desktop.
Save antlis/f4b6bf78ecf0e7ec23feb66d7dce8732 to your computer and use it in GitHub Desktop.
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