Smallest Subtree with all the Deepest Nodes - Problem

Given the root of a binary tree, your task is to find the smallest subtree that contains all the deepest nodes in the tree.

The depth of a node is defined as the shortest distance from the root to that node. The deepest nodes are those nodes that have the maximum depth among all nodes in the tree.

A subtree of a node consists of that node and all its descendants. You need to return the root of the smallest such subtree.

Example: If the deepest nodes are leaves at depth 3, and they have different parents, you need to find their lowest common ancestor that forms the smallest subtree containing all of them.

Input & Output

example_1.py โ€” Python
$ Input: root = [3,5,1,6,2,0,8,null,null,7,4]
โ€บ Output: [2,7,4]
๐Ÿ’ก Note: The deepest nodes are 7 and 4 at depth 3. The smallest subtree containing both is rooted at node 2.
example_2.py โ€” Python
$ Input: root = [1]
โ€บ Output: [1]
๐Ÿ’ก Note: The tree has only one node, so it's both the deepest and the answer.
example_3.py โ€” Python
$ Input: root = [0,1,3,null,2]
โ€บ Output: [2]
๐Ÿ’ก Note: The deepest node is 2 at depth 2. The smallest subtree containing it is just node 2 itself.

Constraints

  • The number of nodes in the tree will be in the range [1, 500]
  • -500 โ‰ค Node.val โ‰ค 500
  • The values of the nodes in the tree are unique

Visualization

Tap to expand
Family Tree: Find Common Ancestor of Youngest Generation๐Ÿ‘ดGreat-Grandpa๐Ÿ‘จGrandpa A๐Ÿ‘จGrandpa B๐Ÿ‘ฆDad 1๐Ÿ‘ฆDad 2๐Ÿ‘ฆDad 3๐Ÿ‘ฆDad 4๐Ÿ‘ถKid A๐Ÿ‘ถKid B๐Ÿ‘ถKid C๐Ÿ‘ถKid DAnswer: Great-Grandpa (root) is the LCA of all youngest kids!๐Ÿ” Algorithm Insight:Kids A, B, C, D are all at depth 3 (youngest generation). Their lowest common ancestoris Great-Grandpa at the root - he represents the smallest family tree containing all youngest members.
Understanding the Visualization
1
Identify Deepest Level
Find all nodes at the maximum depth - these are like the youngest generation in a family
2
Find Common Ancestor
The answer is the lowest common ancestor of all deepest nodes - the closest family connection
3
Single Pass Solution
Instead of multiple passes, calculate depths and find LCA simultaneously using post-order traversal
Key Takeaway
๐ŸŽฏ Key Insight: The problem reduces to finding the LCA of all deepest nodes, which can be solved optimally in O(n) time with a single DFS that compares subtree depths.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen