#865
Smallest Subtree with all the Deepest Nodes
MediumHash TableTreeDepth-First SearchBreadth-First SearchBinary TreeDepth-First SearchLowest Common Ancestor
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)
The optimal solution uses a single DFS traversal to find the deepest nodes and their common ancestor. This is efficient because we only traverse the tree once.
⚙️
Algorithm
3 steps- 1Step 1: Perform a DFS to find the maximum depth of the tree while keeping track of the deepest nodes.
- 2Step 2: During the DFS, if both left and right depths are equal, the current node is a candidate for the smallest subtree containing all deepest nodes.
- 3Step 3: Return the node that is found to be the lowest common ancestor of the deepest nodes.
solution.py29 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 subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
10 def dfs(node):
11 if not node:
12 return 0
13 left_depth = dfs(node.left)
14 right_depth = dfs(node.right)
15 if left_depth == right_depth:
16 return left_depth + 1
17 return max(left_depth, right_depth) + 1
18
19 return self.findLCA(root)
20
21 def findLCA(self, node):
22 if not node:
23 return None
24 left = self.findLCA(node.left)
25 right = self.findLCA(node.right)
26 if left and right:
27 return node
28 return left if left else right
29ℹ
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.
- 1The deepest nodes can be found using a single DFS traversal.
- 2The lowest common ancestor of all deepest nodes is the smallest subtree containing them.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.