Skip to contentKEEP THE CRAFTTHE SANCTUARY

Lowest Common Ancestor in a BST

Find the lowest common ancestor of two values in a binary search tree.

The problem

Implement Solution.lowestCommonAncestor(root, pValue, qValue). root is the root TreeNode of a valid binary search tree with unique values: everything in a node's left subtree is smaller than the node, and everything in its right subtree is larger. pValue and qValue are two different values that both appear in the tree, in either order. Return the value of their lowest common ancestor: the deepest node that has both of them in its subtree. A node counts as part of its own subtree, so if one value sits above the other, that value is the answer. Return an int. Trees are written in level order with None for a missing child. In [6, 2, 8, 0, 4, 7, 9, None, None, 3, 5], the values 2 and 8 give 6, and the values 2 and 4 give 2. Constraints: the tree has 2 to 100,000 nodes with values from -1,000,000,000 to 1,000,000,000. Do not change the tree.

Starter code

class Solution:
    def lowestCommonAncestor(self, root, pValue, qValue):
        pass

Public examples

  1. root = [6, 2, 8, 0, 4, 7, 9, None, None, 3, 5], pValue = 2, qValue = 8gives6
  2. root = [2, 1, 3], pValue = 3, qValue = 1gives2
  3. root = [0, None, 1], pValue = 1, qValue = 0gives0

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.