Skip to main content

Sum All Values in Tree

MIDDLE

Sum All Values in Tree

Calculate sum of all numeric values in a tree structure.

Requirements:

  • Tree has value and children properties
  • Sum all numeric values in tree
  • Traverse all nodes recursively

Example:

const tree = {
  value: 1,
  children: [
    { value: 2, children: [] },
    { value: 3, children: [{ value: 4, children: [] }] }
  ]
};

Input: sumTree(tree)
Output: 10
Explanation: 1 + 2 + 3 + 4 = 10

Examples:

Input 1:{"tree":{"value":1,"children":[{"value":2,"children":[]},{"value":3,"children":[{"value":4,"children":[]}]}]}}
Output 1:10

Loading editor...

Run your code to see results

Click the Run button above