Leetcode 235: Lowest Common Ancestor of a Binary Search Tree

grid47
grid47
Exploring patterns and algorithms
Oct 14, 2024 6 min read

Two paths glowing brightly as they meet at the lowest common ancestor in a binary search tree.
Solution to LeetCode 235: Lowest Common Ancestor of a Binary Search Tree Problem

Given a Binary Search Tree (BST), find the lowest common ancestor (LCA) of two given nodes. The lowest common ancestor is the deepest node that is an ancestor of both nodes. An ancestor of a node is a node itself or any node in its path up to the root.
Problem
Approach
Steps
Complexity
Input: The input consists of the root node of the binary search tree and two target nodes p and q.
Example: Input: root = [5, 3, 8, 2, 4, 7, 9], p = 3, q = 4
Constraints:
• The number of nodes in the tree is between 2 and 10^5.
• Node values are unique.
• The values of p and q are distinct, and both p and q are guaranteed to exist in the tree.
Output: The output should be the node that represents the lowest common ancestor of nodes p and q.
Example: Output: 3
Constraints:
Goal: Find the lowest common ancestor (LCA) in a binary search tree by leveraging the BST property that the left child is smaller and the right child is greater.
Steps:
• If the current node's value is less than both p and q, move to the right subtree.
• If the current node's value is greater than both p and q, move to the left subtree.
• If one of the nodes is smaller and the other is larger, the current node is the LCA.
Goal: Ensure that the solution works within the constraints of a binary search tree and that the nodes p and q exist in the tree.
Steps:
Assumptions:
• The tree is a valid binary search tree.
• The nodes p and q are distinct and guaranteed to exist in the tree.
Input: Input: root = [5, 3, 8, 2, 4, 7, 9], p = 3, q = 4
Explanation: In this tree, the LCA of nodes 3 and 4 is 3 because node 3 is an ancestor of node 4.

Input: Input: root = [6, 2, 8, 0, 4, 7, 9], p = 2, q = 8
Explanation: In this tree, the LCA of nodes 2 and 8 is 6, as 6 is the ancestor of both 2 and 8.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus