Code Logo

Tree Sum Values

Published at25 Jul 2026
Binary Tree Easy 3 views
Like0

Given an array representing a complete binary tree in level-order, compute the sum of all node values in the tree. The sum is the total of every element in the array.

For example, the sum of [1, 2, 3, 4, 5] is 1+2+3+4+5 = 15. The sum of a single-element tree [10] is 10. An empty tree has sum 0. The sum of [5, -3, 2] is 5 + (-3) + 2 = 4.

Summing all values in a tree is a fundamental traversal operation. It requires visiting every node exactly once and accumulating the values. The order of traversal (pre-order, in-order, post-order, level-order) does not affect the result since addition is commutative and associative — the sum is always the same regardless of the order in which nodes are visited.

For an array-based tree, summation is simply iterating through the array and adding all elements. This runs in O(n) time with O(1) extra space. For pointer-based trees, you would use a recursive traversal or an explicit stack to visit all nodes, still O(n) time but requiring O(log n) to O(n) space for the recursion stack.

Edge cases include an empty tree (return 0), a single-node tree (return that node's value), a tree containing negative values (the sum correctly reflects signed addition), and a tree with all zero values (return 0).

Example Input & Output

Example 1
Input
[]
Output
0
Explanation

Empty

Example 2
Input
[10]
Output
10
Explanation

Single node

Example 3
Input
[1,2,3,4,5,6,7]
Output
28
Explanation

Complete tree

Example 4
Input
[1,2,3,4,5]
Output
15
Explanation

Tree as array, sum all values

Example 5
Input
[5,10,15]
Output
30
Explanation

Three nodes

Algorithm Flow

Recommendation Algorithm Flow for Tree Sum Values

Solution Approach

Iterate through the array and accumulate the sum of all elements.

function solution(arr) {
  var sum = 0;
  for (var i = 0; i < arr.length; i++) sum += arr[i];
  return sum;
}

Initialize sum to 0. Loop through every element in the array, adding each to the total. Return the accumulated sum after the loop completes.

For pointer-based trees, use a recursive or stack-based traversal: visit each node, add its value to the total, then recursively process left and right children.

Time complexity is O(n), space complexity is O(1).

Best Answers

java
class Solution {
    public int solution(int[] nums) {
        int s=0;for(int n:nums)s+=n;return s;
    }
}