Lowest Common Ancestor of a Binary Search Tree

Pattern: Search, insert and delete

medium

In a BST, if both values are smaller than the current node the meeting point is on the left; if both are larger it is on the right; otherwise the paths split here and this node is the answer.

The problem

Given a BST and two of its nodes p and q, return their lowest common ancestor. Values are different. For the example, 2 and 8 give 6, and 2 and 4 give 2. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • If both values are below the node, where is their LCA?
  • When do the two search paths separate?
  • Do you need recursion?

Hints

    Brute force, and why it fails

    Use the general binary-tree LCA: O(n).

    The key insight

    The BST order tells you which side both nodes are on without searching, so the LCA is found on one path.

    Dry run

    answer6

    BST [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5], p = 2, q = 8. At 6: 2 < 6 < 8, they split.

    Step 1 of 3

    The plan

    n = root
    loop: if both < n.val: n = n.left
          elif both > n.val: n = n.right
          else: return n
    

    Complexity

    Time
    O(h)
    Space
    O(1)

    One path down.

    Edge cases

    • One node is an ancestor of the other.
    • Both on the same side for many levels.
    • The root is the answer.
    I've built my logic, show the code

    Java

    class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            TreeNode n = root;
            while (true) {
                if (p.val < n.val && q.val < n.val) n = n.left;          // both on the left
                else if (p.val > n.val && q.val > n.val) n = n.right;    // both on the right
                else return n;                                           // they split here (or one of them is n)
            }
        }
    }

    C++

    class Solution {
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            TreeNode* n = root;
            while (true) {
                if (p->val < n->val && q->val < n->val) n = n->left;      // both on the left
                else if (p->val > n->val && q->val > n->val) n = n->right;   // both on the right
                else return n;                                           // they split here (or one of them is n)
            }
        }
    };

    Python

    class Solution:
        def lowestCommonAncestor(self, root, p, q):
            n = root
            while True:
                if p.val < n.val and q.val < n.val:
                    n = n.left                      # both on the left
                elif p.val > n.val and q.val > n.val:
                    n = n.right                     # both on the right
                else:
                    return n                        # they split here (or one of them is n)

    Common mistakes

    • Comparing only one of the two values.
    • Using the general O(n) method.

    Similar problems