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]
💡 Note: The deepest nodes are 7 and 4 at depth 3. The smallest subtree containing both is rooted at node 2, so we return 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
Smallest Subtree with Deepest Nodes INPUT 3 5 1 6 2 0 8 7 4 depth 0 depth 1 depth 2 depth 3 [3,5,1,6,2,0,8,null,null,7,4] Deepest nodes: 7, 4 (at depth 3) ALGORITHM STEPS (DFS) 1 DFS Traversal Find depth of each node 2 Find Max Depth Max depth = 3 (nodes 7, 4) 3 Find LCA Lowest Common Ancestor 4 Return Subtree Smallest subtree root DFS Returns (depth, node) Node 7: (3, 7) - deepest Node 4: (3, 4) - deepest Node 2: (3, 2) - LCA! Both children at max depth LCA of 7 and 4 is node 2 FINAL RESULT Smallest Subtree: 2 7 4 Output: [2, 7, 4] OK - Verified! Contains all deepest nodes (7 and 4) Smallest such subtree Key Insight: The DFS approach returns both the maximum depth found in a subtree and the node that should be the answer. If both children have the same maximum depth, the current node is the LCA of all deepest nodes. Time Complexity: O(n) | Space Complexity: O(h) where h is tree height TutorialsPoint - Smallest Subtree with all the Deepest Nodes | DFS Approach
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