Skip to content

Integer binary tree with depth and max

Question

Implement a binary tree of integers. How should an empty tree be represented? Write functions returning the tree's depth and its largest element.

Short answer

Nodes hold a value and two child pointers; the empty tree is a null pointer. Depth is recursive: 00 for empty, otherwise 1+max⁡1+\max of the children's depths. The maximum is the larger of the node value and the children's maxima, but it is undefined for an empty tree, so throw, return an optional or require non-empty input. Both are O(n)O(n) time and O(h)O(h) stack; manage node memory with smart pointers.

Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q7.30, p.233; 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