Find the median of BST in O(n) time and O(1) space
Pattern: Kth smallest
Count the nodes, then walk inorder with Morris traversal, which needs no stack: link each node's inorder predecessor back to it, use the link to return, then remove it. Pick out the middle value, or the two middle values for an even count.
The problem
Return the median of the values in a non-empty BST: the middle value, or the mean of the two middle values when the count is even. Use O(1) extra space. The tests print the answer with four decimal places.
Think first
- Which positions in the sorted order are the middle?
- What makes inorder take O(h) space normally?
- How can a walk get back up without a stack?
Hints
Brute force, and why it fails
Collect the inorder into an array and read the middle: O(n) space.
The key insight
Morris traversal uses the empty right pointers of predecessors as temporary threads, so the walk needs no stack.
Dry run
| n | 7 |
|---|
BST [6, 3, 8, 1, 4, 7, 9]: 7 nodes, so the median is the 4th in inorder.
The plan
cur = root
while cur:
if no left: visit cur; cur = cur.right
else: p = far right of cur.left
if p.right is null: p.right = cur; cur = cur.left
else: p.right = null; visit cur; cur = cur.right
Complexity
- Time
O(n)- Space
O(1)
Each edge is walked a constant number of times; only a few variables are used. Counting the nodes first uses recursion here, which a second Morris pass could replace.
Edge cases
- One node.
- Two nodes: their mean.
- Even counts.
I've built my logic, show the code
Java
class Solution {
public double findMedian(TreeNode root) {
int n = count(root);
int a = (n + 1) / 2, b = n / 2 + 1; // the 1-based positions of the middle value(s)
int seen = 0, va = 0, vb = 0;
TreeNode cur = root;
while (cur != null) { // Morris inorder: threads instead of a stack, O(1) space
if (cur.left == null) {
seen++;
if (seen == a) va = cur.val;
if (seen == b) vb = cur.val;
cur = cur.right;
} else {
TreeNode p = cur.left;
while (p.right != null && p.right != cur) p = p.right;
if (p.right == null) { p.right = cur; cur = cur.left; } // thread back to cur, go left
else {
p.right = null; // the thread is used: remove it and visit cur
seen++;
if (seen == a) va = cur.val;
if (seen == b) vb = cur.val;
cur = cur.right;
}
}
}
return n % 2 == 1 ? va : (va + vb) / 2.0;
}
private int count(TreeNode n) {
return n == null ? 0 : 1 + count(n.left) + count(n.right);
}
}C++
class Solution {
public:
double findMedian(TreeNode* root) {
int n = count(root);
int a = (n + 1) / 2, b = n / 2 + 1; // the 1-based positions of the middle value(s)
int seen = 0, va = 0, vb = 0;
TreeNode* cur = root;
while (cur != NULL) { // Morris inorder: threads instead of a stack, O(1) space
if (cur->left == NULL) {
seen++;
if (seen == a) va = cur->val;
if (seen == b) vb = cur->val;
cur = cur->right;
} else {
TreeNode* p = cur->left;
while (p->right != NULL && p->right != cur) p = p->right;
if (p->right == NULL) { p->right = cur; cur = cur->left; } // thread back to cur, go left
else {
p->right = NULL; // the thread is used: remove it and visit cur
seen++;
if (seen == a) va = cur->val;
if (seen == b) vb = cur->val;
cur = cur->right;
}
}
}
return n % 2 == 1 ? va : (va + vb) / 2.0;
}
int count(TreeNode* n) {
return n == NULL ? 0 : 1 + count(n->left) + count(n->right);
}
};Python
class Solution:
def findMedian(self, root) -> float:
def count(n):
return 0 if n is None else 1 + count(n.left) + count(n.right)
n = count(root)
a, b = (n + 1) // 2, n // 2 + 1 # the 1-based positions of the middle value(s)
seen, va, vb, cur = 0, 0, 0, root
while cur: # Morris inorder: threads instead of a stack, O(1) space
if cur.left is None:
seen += 1
va = cur.val if seen == a else va
vb = cur.val if seen == b else vb
cur = cur.right
else:
p = cur.left
while p.right and p.right is not cur:
p = p.right
if p.right is None:
p.right, cur = cur, cur.left # thread back to cur, go left
else:
p.right = None # the thread is used: remove it and visit cur
seen += 1
va = cur.val if seen == a else va
vb = cur.val if seen == b else vb
cur = cur.right
return float(va) if n % 2 else (va + vb) / 2Common mistakes
- Leaving threads in the tree.
- Integer division when averaging.