Smallest Subtree with all the Deepest Nodes (LeetCode 865): Solution and Explanation

Medium
Hash Table
Tree
Depth First Search
Breadth First Search
Binary Tree

Find the lowest node whose subtree contains every deepest node of a binary tree. One post-order pass returns each subtree's height together with the best candidate inside it.

Intuition

The deepest nodes of a subtree always sit on its taller side. If the left child's subtree is taller, nothing on the right can be deepest, so the answer for this node is simply the answer for its left child.

When both sides have the same height, deepest nodes exist on both sides. No node below the current one can cover both sides, so the current node is the smallest cover.

That means each call needs two facts from its children: how tall they are and which node they would answer. Returning both as a pair lets one bottom-up pass settle every node, and the root's candidate is the final answer.

Approach: Post-order DFS returning (height, candidate)

  1. dfs(None) returns (0, None).
  2. For a node, compute (ld, ln) = dfs(node.left) and (rd, rn) = dfs(node.right).
  3. If ld > rd, return (ld + 1, ln): the deepest nodes are all on the left.
  4. If rd > ld, return (rd + 1, rn): the deepest nodes are all on the right.
  5. Otherwise return (ld + 1, node): the node covers deepest nodes on both sides.
  6. Return the candidate from dfs(root).

Step-by-step example

root = [3,5,1,6,2,0,8,null,null,7,4]
  1. The leaves 6, 7, 4, 0 and 8 each return height 1 with themselves as candidate.
  2. Node 2: both children have height 1, a tie, so it returns (2, 2).
  3. Node 5: left child 6 has height 1 and right child 2 has height 2, so it returns (3, 2).
  4. Node 1: children 0 and 8 tie at height 1, so it returns (2, 1).
  5. Root 3: left height 3 beats right height 2, so it returns (4, 2). The answer is the subtree [2,7,4].

Code: Python, Java, C++

1class Solution:
2    def subtreeWithAllDeepest(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
3        def dfs(node):
4            if not node:
5                return 0, None
6            ld, lnode = dfs(node.left)
7            rd, rnode = dfs(node.right)
8            if ld > rd:
9                return ld + 1, lnode
10            if rd > ld:
11                return rd + 1, rnode
12            return ld + 1, node
13        return dfs(root)[1]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each node is visited once and does constant work after both children return.

Space

O(h)

The recursion stack grows to the tree height h, which is n for a chain.

Other approaches

BFS then lowest common ancestor (time O(n), space O(n))

Find all nodes on the last level with a BFS, record parents, then walk all of them upward together until they meet. Two passes and a parent map instead of one recursion.

Repeated depth queries (time O(n^2), space O(h))

At each node, compute the heights of both children with a separate depth function and move toward the taller side. Simple but recomputes heights, giving O(n^2) on a skewed tree.

Common mistakes

  • Returning the deepest leaf instead of the subtree root that covers all deepest leaves when there are several.
  • Recomputing the height at every node with a separate function, which turns the solution quadratic.
  • Breaking ties toward one side. A tie means deepest nodes exist on both sides, so the current node must be the answer.
  • Comparing depths from the root instead of subtree heights; either works if done consistently, but mixing them gives wrong comparisons.

Frequently asked questions

Is this the same as Lowest Common Ancestor of Deepest Leaves?

Yes. LeetCode 1123 asks the same question with different wording, and the same (height, candidate) DFS solves both.

What if there is only one deepest node?

Then the smallest subtree containing it is the node itself. The DFS gives that naturally, because a leaf returns itself and its ancestors always pass it up from the taller side.

Why return the node rather than its value?

The problem asks for the subtree, so the function returns the node, and the whole subtree under it is the answer.