Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Sum of Nodes

Treeseasy

Implement `treeSum(root)` returning the sum of all node values (0 for an empty tree).

Sample tests

Input: treeSum({"val":1,"left":{"val":2,"left":null,"right":null},"right":{"val":3,"left":null,"right":null}})
Output: 6
Input: treeSum(null)
Output: 0

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Missing the null base case.

Learning resources

  • Wikipedia: Binary tree
Approach & explanation (try first)

Each node contributes its value plus the sums of its subtrees. O(n).

Loading...
⌘/Ctrl + Enter

Run your code to see results.