#1123
Lowest Common Ancestor of Deepest Leaves
MediumHash TableTreeDepth-First SearchBreadth-First SearchBinary TreeDepth-First SearchTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(h) |
💡
Intuition
Time O(n)Space O(h)
This approach uses a single DFS traversal to find the deepest leaves and their lowest common ancestor simultaneously. By returning both the depth and the node, we avoid multiple passes over the tree.
⚙️
Algorithm
4 steps- 1Step 1: Perform a DFS that returns both the depth of the deepest leaves and the lowest common ancestor of those leaves.
- 2Step 2: If a node is a leaf, return its depth and itself.
- 3Step 3: If both left and right children return a depth, the current node is the LCA.
- 4Step 4: If only one child returns a depth, propagate that child back up.
solution.py23 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8class Solution:
9 def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
10 def dfs(node):
11 if not node:
12 return (0, None)
13 left_depth, left_lca = dfs(node.left)
14 right_depth, right_lca = dfs(node.right)
15 if left_depth > right_depth:
16 return (left_depth + 1, left_lca)
17 elif right_depth > left_depth:
18 return (right_depth + 1, right_lca)
19 else:
20 return (left_depth + 1, node)
21
22 return dfs(root)[1]
23ℹ
Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.
- 1Understanding the concept of depth and how it relates to leaves is crucial.
- 2Recognizing that a single DFS can solve the problem efficiently is key to optimizing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.