Skip to main content

Find Largest Smaller BST Key

Hard

Given a root of a Binary Search Tree (BST) and a number num, implement an efficient function findLargestSmallerKey that finds the largest key in the tree that is smaller than num. If such a number doesn't exist, return -1. Assume that all keys in the tree are nonnegative.

For example: For num = 17 and the binary search tree below:

img_02

Your function would return: 14 since it’s the largest key in the tree that is still smaller than 17.

Give it a try using the code editor!

Need a refresher on Binary Search Trees? Check out Exponent's lesson on Trees or take this interactive BST visualizer out for a spin.

Some candidates look first for num in the tree, then look for its predecessor. But num isn't necessarily a key — it could be any number.

Can you explain why it's possible to always store the last key smaller than num without comparing it to the previously stored key?