Shared Root of Two Nodes in a Binary Search Tree
Trees & GraphsAuto-graded · 21 test casesLast updated
Tests whether a candidate can exploit BST ordering to locate the deepest node that is an ancestor of both targets without searching the entire tree.
Shared Root of Two Nodes in a Binary Search Tree
A Binary Search Tree (BST) has a useful structural guarantee: for any node with value v, every value in its left subtree is less than v and every value in its right subtree is greater than v.
Given a BST (as a level-order list) and two target values p and q, return the value of their meeting point — the deepest node in the tree that is an ancestor of both.
A node counts as an ancestor of itself, so if one target is a direct ancestor of the other, that ancestor is the answer.
Input format
The tree arrives as a level-order list following the standard convention:
- Integer entries are node values.
Nonemarks a missing child slot.Nonenodes do not contribute child slots of their own.
For example, [6, 2, 8, 0, 4, 7, 9, None, None, 3, 5] represents:
6
/ \
2 8
/ \ / \
0 4 7 9
/ \
3 5
Task
Return the value of the deepest common ancestor of p and q.
Return None if the input list is empty or its first entry is None.
Constraints
- The number of nodes in the tree is in the range
[2, 10^5]. -10^9 <= node value <= 10^9- All node values are unique.
- Both
pandqare guaranteed to exist in the BST. pandqmay be equal.- The input list may be
[]or[None], in which case returnNone.
Examples
Example 1
Input: bst_meeting_point([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5], 2, 8)
Output: 6
Example 2
Input: bst_meeting_point([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5], 2, 4)
Output: 2
Example 3
Input: bst_meeting_point([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5], 7, 9)
Output: 8
Hints
Hint 1
At any node, if both targets are smaller than the current value they must both live in the left subtree — and so does their meeting point. The same logic applies to the right. When do you know you've found the answer without going deeper?
Hint 2
The meeting point is the first node where the two targets stop travelling in the same direction. Think about what it means for p to be on one side and q on the other — or for one of them to equal the current node.
Hint 3
Build the tree from the level-order list using a queue: dequeue one parent at a time and assign the next two list entries as its left and right children, skipping None slots (but still advancing your read position past them).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight: the split-point argument
In a BST, the path from the root to any node is fully determined by comparisons with each node along the way. Picture the path from the root down to p and the separate path down to q. Those two paths start at the root and at some point diverge — they share a prefix, then go in different directions. The deepest node they share is exactly the meeting point we want.
At any node with value cur:
- If both
pandqare less thancur, both target paths go left, so the meeting point also lies in the left subtree. Move left. - If both are greater than
cur, both paths go right. Move right. - Otherwise, stop. Either the targets split (
p < cur < qor the reverse), meaningcuris where their paths diverge, or one of them equalscur, meaningcuris an ancestor of itself and of the other target. Either way,curis the answer.
The loop never needs to locate p or q explicitly — the comparison logic steers directly to the answer.
Why this is correct
The argument above covers every case:
- Meeting point is the root: the very first comparison triggers the "else" branch and returns immediately.
- One target is an ancestor of the other: when
curequalsp(orq), the other target must live somewhere incur's subtree (because all prior steps moved toward both targets). Since a node is its own descendant,curis the correct answer. p == q: neither strict inequality holds at the node wherecur == p == q, so the else branch fires and returns it.p > q: the comparisons are symmetric, so the order of the two targets does not matter.
Building the tree from the level-order list
The input follows the standard level-order convention. Parsing it requires a BFS-style pass:
- Create a record for the root value and add it to a queue of parents waiting for children.
- Dequeue one parent at a time and read the next two entries from the list as its left and right children.
- If an entry is not
None, create a record for that child value, link it to the parent, and enqueue it as a future parent. - Always advance the read position past both slots, even when a slot holds
None.
Because all values are unique, a plain dictionary keyed by value is enough to store the tree — no TreeNode objects are needed.
Complexity
| Phase | Time | Space |
|---|---|---|
| Parsing the level-order list | O(n) | O(n) |
| BST descent to the meeting point | O(h) | O(1) |
Where n is the number of nodes and h is the tree height. For a balanced BST h = O(log n); for a degenerate (fully skewed) BST h = O(n). The parsing step dominates, so the overall complexity is O(n) time and O(n) space.
The descent loop is iterative, avoiding Python's recursion-depth limit for trees with up to 10^5 nodes.
Reference solution
from typing import List, Optional
def bst_meeting_point(root: List[Optional[int]], p: int, q: int) -> Optional[int]:
if not root or root[0] is None:
return None
# Reconstruct the BST from the level-order list.
# Each entry in `nodes` maps a value to [value, left_value, right_value].
nodes = {root[0]: [root[0], None, None]}
queue = [root[0]]
pos = 1 # next index to read from `root`
head = 0 # index of the next parent to process in `queue`
while head < len(queue) and pos < len(root):
value = queue[head]
head += 1
node = nodes[value]
# Left child slot
if pos < len(root) and root[pos] is not None:
left = root[pos]
node[1] = left
nodes[left] = [left, None, None]
queue.append(left)
pos += 1
# Right child slot
if pos < len(root) and root[pos] is not None:
right = root[pos]
node[2] = right
nodes[right] = [right, None, None]
queue.append(right)
pos += 1
# Walk down from the root, using BST ordering to choose a direction.
current = root[0]
while current is not None:
if p < current and q < current:
current = nodes[current][1] # both targets in left subtree
elif p > current and q > current:
current = nodes[current][2] # both targets in right subtree
else:
return current # paths diverge here, or current equals p or q
return None