Skip to content

Adding up all node values in a binary tree

Question

Each node of a tree stores a number and has at most two children. Write a routine that returns the total of all node values.

Short answer

Recursive traversal: sum(node) is 00 for an empty node, else its value plus the sums of both subtrees. Every node is visited once, so time is O(n)O(n) and the stack depth is the tree height hh. For very deep, unbalanced trees, use an explicit stack or queue to avoid stack overflow.

Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q5.19, p.159; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question