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 for an empty node, else its value plus the sums of both subtrees. Every node is visited once, so time is and the stack depth is the tree height . 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