Leetcode 236: Lowest Common Ancestor of a Binary Tree

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

Similar to the previous idea, with paths gently intersecting to show the common ancestor in a non-search tree.
Solution to LeetCode 236: Lowest Common Ancestor of a Binary Tree Problem

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes. The lowest common ancestor is defined as the lowest node that is an ancestor of both nodes p and q. A node can be a descendant of itself.
Problem
Approach
Steps
Complexity
Input: The input consists of the root of the binary tree and two nodes, p and q, whose lowest common ancestor is to be found.
Example: Input: root = [4, 2, 6, 1, 3, 5, 7], p = 2, q = 6
Constraints:
• The number of nodes in the tree is between 2 and 10^5.
• Node values are unique.
• Both p and q exist in the tree.
Output: The output should be the node that represents the lowest common ancestor of nodes p and q.
Example: Output: 4
Constraints:
Goal: Find the lowest common ancestor (LCA) of nodes p and q in the binary tree using a recursive approach.
Steps:
• Start from the root node.
• If the current node is null, return null.
• If the current node is equal to either p or q, return that node.
• Recursively search the left and right subtrees for p and q.
• If both left and right subtrees return non-null values, the current node is the LCA.
• If only one of the subtrees returns a non-null value, return that node.
Goal: The problem assumes the tree is a valid binary tree and that p and q are distinct and exist in the tree.
Steps:
Assumptions:
• The tree is a valid binary tree.
• The nodes p and q are distinct and exist in the tree.
Input: Input: root = [4, 2, 6, 1, 3, 5, 7], p = 2, q = 6
Explanation: In this tree, the LCA of nodes 2 and 6 is 4, as 4 is the ancestor of both nodes.

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

Link to LeetCode Lab


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