Problem 46

Tree Sum Recursion Challenge

Given a tree node, return the sum of all value properties in the tree. Each node is an object with a numeric value and a children array containing zero or more child nodes of the same shape.

Function Signature

treeSum(node)

Parameters

  • node — a tree node with the structure {value: number, children: [node, ...]}.

Data Structure

{
  value: number,
  children: Array  // each element is a node with the same shape
}

Output

Return a number representing the sum of all node values in the tree.

Constraints

  • The function must use recursion.
  • The input tree must not be mutated.
  • The function should accept exactly one argument.

Examples

treeSum({value: 7, children: []}) → 7

treeSum({
  value: 5,
  children: [
    {value: 3, children: []},
    {value: 2, children: [
      {value: 4, children: []},
      {value: 6, children: []}
    ]}
  ]
}) → 20

treeSum({value: -1, children: [{value: 2, children: [{value: -3, children: []}]}]})
→ -2