DevPath

← All problems

Sum of Tree Values

Easy trees

Description

Return the sum of all non-null node values.

Constraints

0 <= n <= 100000

Examples

Input: tree = [1,2,3]

Output: 6

Hints (1)
  • Ignore nulls and sum the rest.

Solutions

Sum non-null values. · Time O(n) · Space O(1)

func treeSum(tree []interface{}) int {
    sum := 0
    for _, v := range tree {
        if n, ok := v.(float64); ok {
            sum += int(n)
        }
    }
    return sum
}

Create a free account to submit solutions, track progress and save problems.

Create account