मुख्य कंटेंट तक स्किप करें
Back to ChallengesSum of All NodesEasy 15 min

Sum of All Nodes

Given the root of a binary tree, return the **sum of all node values** in the tree.

Examples

Input: root = [1,2,3,4,5]
Output: 15
1+2+3+4+5 = 15.
Input: root = [-1,2,-3]
Output: -2
-1+2+(-3) = -2.

Constraints

  • Number of nodes in [0, 10^4]
  • -1000 <= Node.val <= 1000

Complexity Analysis

Time
O(n)
Space
O(h)

Test Cases

#1 Positive values
Input: [1,2,3,4,5]
Expected: 15
#2 Mixed signs
Input: [-1,2,-3]
Expected: -2
#3 Empty tree
Input: []
Expected: 0
#4 Single node
Input: [7]
Expected: 7
JavaScript
Output
Click "Run Code" to see output here...