Smallest Subtree with all the Deepest Nodes — LeetCode 865 Python Solution

MediumTreeDepth-First SearchBreadth-First SearchHash TableBinary Tree
Problem
#865
Reading time
4 min

The problem

Given the root of a binary tree, the depth of each node is the shortest distance to the root. Return the smallest subtree such that it contains all the deepest nodes in the original tree.

Example

Input
root = [3,5,1,6,2,0,8,null,null,7,4]
Output
[2,7,4]
Explanation
We return the node with value 2, colored in yellow in the diagram.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def subtreeWithAllDeepest(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def dfs(root: Optional[TreeNode]) -> Tuple[Optional[TreeNode], int]:
            if root is None:
                return None, 0
            l, ld = dfs(root.left)
            r, rd = dfs(root.right)
            if ld > rd:
                return l, ld + 1
            if ld < rd:
                return r, rd + 1
            return root, ld + 1

        return dfs(root)[0]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 865. Smallest Subtree with all the Deepest Nodes is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 865. Smallest Subtree with all the Deepest Nodes?
LeetCode 865. Smallest Subtree with all the Deepest Nodes is rated Medium on LeetCode.
What is the time complexity of LeetCode 865. Smallest Subtree with all the Deepest Nodes?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 865. Smallest Subtree with all the Deepest Nodes?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 865. Smallest Subtree with all the Deepest Nodes cover?
LeetCode 865. Smallest Subtree with all the Deepest Nodes is tagged Tree, Depth-First Search, Breadth-First Search, Hash Table and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview