LeetCode 236. Lowest Common Ancestor of a Binary Tree
🧩 Problem Description
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes p
and q
.
The lowest common ancestor is defined between two nodes
p
andq
as the lowest node in the tree that has bothp
andq
as descendants (where we allow a node to be a descendant of itself).
💬 Example
Example 1
1 | Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 |
Example 2
1 | Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 |
💡 Approach: Recursive DFS
We traverse the binary tree recursively:
- If the current node is
null
, returnnull
. - If the current node matches
p
orq
, return it. - Recursively search left and right subtrees.
- If both left and right return non-null, the current node is the LCA.
- Otherwise, return the non-null child.
🔢 Java Code
1 | class Solution {{ |
⏱ Time and Space Complexity
- Time Complexity: O(n) — visiting each node once
- Space Complexity: O(h) — recursion stack, where h is the tree height
✍️ Summary
- This is a classic DFS + recursion problem on binary trees.
- We find the split point where
p
andq
diverge in different subtrees. - Related problems:
lc-235
— LCA of a BST (simpler due to BST property)lc-236
— LCA of any binary tree (this one)