Kth smallest
The inorder of a BST lists the values in increasing order, so the kth smallest is the kth value an inorder walk visits; stop there. The median needs the middle one or two values, and Morris traversal finds them with O(1) extra space by threading temporary links back to each node's successor.
How to recognise it
- The kth smallest or largest value in a BST.
- The median of a BST.
- O(1) extra space for a traversal.
Inorder is sorted
stack = []; n = root
loop:
while n: push n; n = n.left
n = pop; k -= 1
if k == 0: return n.val
n = n.right
The rule that makes a BST, and how it compares with a heap, is on the Structures page.
Morris traversal
For a node with a left subtree, find its inorder predecessor (the far right of the left subtree). If that node's right link is empty, point it at the current node and go left. If it already points back, the left side is done: remove the thread, visit the node, and go right. Every edge is walked at most a few times, so it is O(n) time and O(1) space.
Common mistakes
- Counting k from 0 instead of 1.
- Leaving Morris threads in place when stopping early.
Problems
- Kth Smallest Element in a BSTmediumguide ready
- Find the median of BST in O(n) time and O(1) spacemediumguide ready