Skip to content
BytePatterns

Kth Smallest BST Key, Iteratively

MediumRecursion#explicit-stack#inorder~25m

Problem

A binary search tree holds distinct integer keys. Given its root and a number k, return the k-th smallest key, counting from 1, or None if the tree has fewer than k keys. Do it without recursion, since the tree may be a chain far deeper than the call stack allows, and stop as soon as the answer is known.

Examples

Input:  tree = 8, left 3 with children 1 and 6 (6 has children 4 and 7),
        right 10 with a right child 14; k = 4
Output: 6
Why:    in order the keys read 1, 3, 4, 6, 7, 8, 10, 14
Input:  same tree; k = 8
Output: 14
Why:    the largest key is the last one in order
Input:  same tree; k = 9
Output: None
Why:    edge case, the tree holds only eight keys

Hints

0 / 3

Stuck on the idea rather than the code? Your Own Call Stack covers it.