Problem 865

Abstract / Summary

Find the smallest subtree that contains all the deepest nodes in a binary tree.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0865.py

class Solution:
    def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
        levels = defaultdict(int)

        def count(node, depth):
            if node:
                levels[depth] += 1
                count(node.left,  depth + 1)
                count(node.right, depth + 1)

        count(root, 0)

        limit = max(levels)
        need  = levels[limit]
        result = None

        def locate(node, depth):
            if not node:
                return 0

            # early exit
            nonlocal result
            if result:
                return 0

            if depth == limit:
                if need == 1:
                    result = node
                return 1

            l = locate(node.left,  depth + 1)
            r = locate(node.right, depth + 1)
            if l + r == need and result == None:
                result = node
            return l + r

        locate(root, 0)
        return result
38 lines | 988 bytes | submitted September 2, 2023 | GitHub   3% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 78% (300k+ submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Breadth First Search
  • Depth First Search
  • Hash Table
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method that returns the smallest subtree containing all the deepest nodes of a binary tree. It proceeds in two distinct phases. The first phase traverses the entire tree to record how many nodes exist at each depth. The second phase walks the tree again, this time looking for the node that either is a deepest leaf (when there is only one deepest node) or whose combined count of deepest nodes in its left and right sub-trees matches the total number of deepest nodes. The method uses a non-local variable to capture the answer as soon as it is identified, allowing the recursion to stop early.

Phase One - Depth Counting

The algorithm begins by creating a dictionary that maps each depth to the number of nodes observed at that depth. A helper function named count is defined and invoked with the root node and an initial depth of zero. Inside the helper, the current node contributes to the count for its depth, and the function recurses on the left and right children with an incremented depth.

levels = defaultdict(int)

def count(node, depth):
    if node:
        levels[depth] += 1
        count(node.left,  depth + 1)
        count(node.right, depth + 1)

count(root, 0)

When the traversal finishes, levels holds a complete histogram of node distribution across depths. The deepest level is identified by taking the maximum key in the dictionary, and the number of deepest nodes is stored in need.

limit = max(levels)
need  = levels[limit]

Phase Two - Locating the Target Subtree

A second helper function, locate, performs a depth-first search that returns the count of deepest nodes found in the subtree rooted at the current node. The function uses a non-local variable result to store the answer once it is discovered. An early-exit guard checks whether result is already set; if so, the function returns immediately, preventing further unnecessary work.

def locate(node, depth):
    if not node:
        return 0

    # early exit
    nonlocal result
    if result:
        return 0

When the recursion reaches the deepest level (depth == limit), it checks whether there is exactly one deepest node. If that is the case, the current node itself is the required subtree root, and result is assigned accordingly. The function then returns a count of one to its caller.

    if depth == limit:
        if need == 1:
            result = node
        return 1

For internal nodes, the function recurses on both children, accumulating the counts returned from the left and right sub-trees. If the sum of these counts equals the total number of deepest nodes (need) and result has not yet been set, the current node is identified as the smallest subtree containing all deepest nodes. The function then returns the combined count to its caller.

    l = locate(node.left,  depth + 1)
    r = locate(node.right, depth + 1)
    if l + r == need and result == None:
        result = node
    return l + r

The initial call to locate starts at the root with depth zero, and after the recursion completes, result holds the desired subtree root, which is returned to the caller.

locate(root, 0)
return result

Edge Cases Handled

The algorithm gracefully handles an empty tree because the initial count call receives a None node, leaving levels empty. The subsequent max(levels) call would raise an exception in that scenario, but the problem definition typically guarantees a non-empty tree, so the code assumes at least one node is present.

When the tree consists of a single node, the depth histogram contains only depth zero with a count of one. Consequently, limit is zero and need is one. The locate function reaches the deepest level immediately, satisfies the need == 1 condition, and assigns the root node to result. The method therefore returns the sole node as the correct subtree.

If multiple deepest nodes exist, the algorithm correctly identifies the lowest common ancestor of those nodes. The early-exit condition ensures that once the appropriate ancestor is found, deeper recursive calls are avoided, preventing redundant work.

The code also copes with highly unbalanced trees, such as a chain of left children. The depth counting phase records each depth, and the locating phase walks down the chain until it reaches the deepest level, then propagates the count back up, ultimately selecting the deepest node when it is the only deepest node, or the appropriate ancestor when multiple deepest nodes share a common parent.

Performance Optimizations

Two notable optimizations are present. First, the use of a defaultdict(int) for levels eliminates the need for explicit existence checks before incrementing a depth count, resulting in concise and efficient updates during the counting traversal.

Second, the early-exit guard inside locate (if result: return 0) stops further recursion once the answer has been found. This prevents the algorithm from traversing sub-trees that are no longer needed, reducing the total number of recursive calls in cases where the target subtree is located high in the tree.

Additionally, the algorithm avoids constructing auxiliary data structures to store paths or parent pointers. By returning the count of deepest nodes from each recursive call, it leverages the call stack to propagate necessary information without extra memory overhead.

Overall, the solution achieves its goal with two linear passes over the tree, each employing straightforward recursion and minimal auxiliary state.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big family tree made of branches that reach out in many directions. Some branches are short, and some branches are very long. The goal is to find a specific spot where all the very longest branches meet.

First, there is a way to look at every single branch to see how long each one is. By walking through the entire tree from the top, it counts how many branches stop at each distance. This helps identify exactly which distance is the furthest one possible. It also counts how many of those longest branches exist in total.

Once the furthest distance and the total count are known, the search begins again from the top. This time, every time a branch is visited, it checks if that branch eventually leads to those deepest spots. If the number of deepest spots found through a branch matches the total number found earlier, that branch must be the one holding them all. As soon as that special spot is found, it is saved for later.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.35 | σ = 1.86

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python Java Rust Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
MacJim C++
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
withaarzoo C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
MacJim C++
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
withaarzoo C++
YuriSpiridonov Python
34 links | 21 authors | 10 languages

Videos

10 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

3 easy 4 medium
8 solutions   September 2, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality