KatInterview

Shared Root of Two Nodes in a Binary Search Tree

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphsbinary-search-treelowest-common-ancestortree-traversal

Last 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.
  • None marks a missing child slot.
  • None nodes 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 p and q are guaranteed to exist in the BST.
  • p and q may be equal.
  • The input list may be [] or [None], in which case return None.

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).