Tree Sum Values
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
Empty
Single node
Complete tree
Tree as array, sum all values
Three nodes
Algorithm Flow
Solution Approach
Iterate through the array and accumulate the sum of all elements.
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
class Solution {
public int solution(int[] nums) {
int s=0;for(int n:nums)s+=n;return s;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
