↓Skip to main content
  1. LeetCode/

LeetCode 865: Smallest Subtree with all the Deepest Nodes

·2 mins· ·
LeetCode Medium Tree Binary-Tree Bfs Dfs Lca
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2026-01-09

  • Submissions: Accepted (first try)
  • Same problem: LC 1123 Lowest Common Ancestor of Deepest Leaves

Approach
#

“The smallest subtree containing all the deepest nodes” is the lowest common ancestor (LCA) of all the deepest nodes.

My Solution: BFS to the last level, then climb as a group
#

  1. BFS while recording each node’s parent, keeping the nodes of the last level.
  2. Put the last level in a set and move the whole set up one level at a time until one node is left.
from collections import deque

class Solution:
    def subtreeWithAllDeepest(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None

        parent = {root: None}
        q = deque([root])
        last_level = []
        while q:
            last_level = []
            for _ in range(len(q)):
                node = q.popleft()
                last_level.append(node)
                if node.left:
                    parent[node.left] = node
                    q.append(node.left)
                if node.right:
                    parent[node.right] = node
                    q.append(node.right)

        deepest = set(last_level)
        while len(deepest) > 1:
            deepest = {parent[node] for node in deepest}
        return deepest.pop()

All deepest nodes are on the same level, so moving them up together keeps their depths equal. The first time the set collapses to one node, that node is the LCA.

Alternative: one DFS returning (depth, answer)
#

Each node returns the maximum depth of its subtree and the answer node for that subtree:

  • Left is deeper: the answer is in the left subtree.
  • Right is deeper: the answer is in the right subtree.
  • Equal depth: both sides contain deepest nodes, so the answer is the current node.
class Solution:
    def subtreeWithAllDeepest(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def dfs(node):
            if not node:
                return 0, None
            left_depth, left_ans = dfs(node.left)
            right_depth, right_ans = dfs(node.right)
            if left_depth > right_depth:
                return left_depth + 1, left_ans
            if right_depth > left_depth:
                return right_depth + 1, right_ans
            return left_depth + 1, node

        return dfs(root)[1]

Complexity
#

ApproachTimeSpace
BFS + climbingworst O(n * h), each climb step touches the whole setO(n)
DFS returning a tupleO(n)O(h)

Mistakes to Avoid
#

  • Returning one deepest node: there can be several.
  • In the DFS version, returning a child instead of the current node on a tie.

Interview Explanation
#

The smallest subtree containing all deepest nodes is their LCA. I run one post-order DFS where each node returns its subtree’s maximum depth and the answer: whichever side is deeper holds the answer, and if both sides are equally deep, the deepest nodes are split across them, so the answer is the current node. Time O(n), space is the tree height.

Related

LeetCode 1339: Maximum Product of Splitted Binary Tree
·2 mins
LeetCode Medium Tree Binary-Tree Dfs
LeetCode 1339 note: compute the total, enumerate every subtree sum, and leave the input untouched
LeetCode 1161: Maximum Level Sum of a Binary Tree
·2 mins
LeetCode Medium Tree Binary-Tree Bfs
LeetCode 1161 note: pushing None into the next level creates a fake level with sum 0
LeetCode 958: Check Completeness of a Binary Tree
·2 mins
LeetCode Medium Tree Binary-Tree Bfs
LeetCode 958 note: completeness is a global property, so check with BFS whether any node follows the first gap
LeetCode 1306: Jump Game III
·2 mins
LeetCode Medium Bfs Dfs Graph Array
LeetCode 1306 note: indices are nodes and the two jumps are edges; BFS or DFS decides whether a zero is reachable
LeetCode 3619: Count Islands With Total Value Divisible by K
·2 mins
LeetCode Medium Dfs Bfs Matrix Graph
LeetCode 3619 note: flood fill each island and sum its values; with up to 10^5 cells, iterate to avoid deep recursion
LeetCode 1008: Construct Binary Search Tree from Preorder Traversal
·2 mins
LeetCode Medium Tree Bst Binary-Tree Recursion
LeetCode 1008 note: splitting the array is O(n^2); recursing with an upper bound is O(n)