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
Difficulty
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
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 1123: Lowest Common Ancestor of Deepest Leaves
Solved On The Same Day
- problem 563: Binary Tree Tilt
- problem 938: Range Sum of BST
- problem 965: Univalued Binary Tree
- problem 146: LRU Cache
- problem 371: Sum of Two Integers
- problem 1201: Ugly Number III
- problem 2707: Extra Characters in a String
Extra
- 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