Lowest Common Ancestor of a Binary Search Tree

Lowest Common Ancestor of a Binary Search Tree is a Medium Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Tree Traversal Patterns (DFS & BFS) pattern, in the Lowest Common Ancestor (LCA) Finding subpattern.

Problem statement

Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.

According to the definition of LCA on Wikipedia: The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).

Example 1:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6.

Example 2:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

Example 3:

Input: root = [2,1], p = 2, q = 1 Output: 2

Constraints:

- The number of nodes in the tree is in the range [2, 105].

- -109 <= Node.val <= 109

- All Node.val are unique.

- p != q

- p and q will exist in the BST.

Topics and companies

Topics: Tree, Depth-First Search, Binary Search Tree, Binary Tree.

Reported in interviews at Amazon, Facebook, LinkedIn, Oracle, Microsoft.

How to practise Lowest Common Ancestor of a Binary Search Tree on Thita.ai

Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(h), where h is the height of the BST. Building the tree from the vector is O(n), but the LCA search is O(h). time and O(n), where n is the number of nodes in the BST, due to the tree construction and storage. space.

Open Lowest Common Ancestor of a Binary Search Tree in the code editor, or read the Lowest Common Ancestor of a Binary Search Tree editorial for a worked solution with its approach and complexity analysis.

Where Lowest Common Ancestor of a Binary Search Tree sits in the DSA pattern sheet

Problems related to Lowest Common Ancestor of a Binary Search Tree

Other problems that use the same Lowest Common Ancestor (LCA) Finding and Tree Traversal Patterns (DFS & BFS) techniques:

Preparing this workspace.