Closest Number in Binary Search Tree II

In a binary search tree, find k nodes containing the closest numbers to the given target number. return them in sorted array

Assumptions:

  • The given root is not null.

  • There are no duplicate keys in the binary search tree.

Examples:

5

/ \

2 11

/ \

6 14

closest number to 4 is 5

closest number to 10 is 11

closest number to 6 is 6

Solution: inorder traversal with queue

A queue of k size to track window of nodes closest

Traverse inorder sums into two situations:

  • in order towards the target

Nodes that first entered the queue is the furthest away from target, thus can be eliminated first

  • in order away from the target

If new right node are closer to furthest left nodes in window, we can eliminate the furthest left node

TC: O(N) one pass

SC: O(k) k sized queue + O(logN) recursion stack

Last updated

Was this helpful?