Lowest Common Ancestor of a BST
TreeBST
Problem Statement
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
Example
Example 1:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
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.
Solution (Recursive Approach)
The solution uses a recursive approach to find the lowest common ancestor (LCA) of two nodes in a Binary Search Tree (BST). The key property of a BST is that all nodes in the left subtree are smaller than the root, and all nodes in the right subtree are larger.
Algorithm Steps
- If both nodes are smaller than the current node, the LCA must be in the left subtree.
- If both nodes are larger than the current node, the LCA must be in the right subtree.
- If one node is smaller and the other is larger, the current node is the LCA.
Case 1: LCA is the root. Find LCA of 2 and 8.
Case 2: LCA in left subtree. Find LCA of 0 and 4.
Case 3: LCA in right subtree. Find LCA of 7 and 9.
Lowest Common Ancestor of a BST Solution