Python 0572.py
class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
@cache
def serialize(node):
if node:
return "l=" + serialize(node.left) + "|" + str(node.val) + "|r=" + serialize(node.right)
else:
return ""
lookfor = serialize(subRoot)
result = False
def deeper(node):
if node:
nonlocal lookfor, result
if serialize(node) == lookfor:
result = True
return
deeper(node.left)
deeper(node.right)
deeper(root)
return result
Difficulty
and has an acceptance rate of about 52% (2+ million submissions).
Typical patterns to solve this problem:
- Binary Tree
- Depth First Search
- Hash Function
- String Matching
- 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 determines whether a binary tree subRoot appears as a subtree of another binary tree root. It does this by converting each subtree into a canonical string representation and then searching for a match of the subRoot representation within the larger tree. The algorithm relies on recursion for both serialization and traversal, and it leverages Python’s built-in caching mechanism to avoid redundant work.
Key Steps
The first major component is a recursive serializer that produces a unique string for any given node. The serializer is wrapped with the @cache decorator, which stores the result of each call keyed by the node object, ensuring that repeated visits to the same node do not recompute its string.
@cache
def serialize(node):
if node:
return "l=" + serialize(node.left) + "|" + str(node.val) + "|r=" + serialize(node.right)
else:
return ""
The serializer encodes the left subtree, the current node’s value, and the right subtree, separating each part with delimiters (l=, |, r=). An empty string is returned for a None child, which guarantees that structural differences (such as missing children) are reflected in the final representation.
After defining the serializer, the code creates the target pattern by serializing subRoot once:
lookfor = serialize(subRoot)
result = False
The next phase is a depth-first walk of root. A nested function deeper visits each node, compares its serialized form with lookfor, and sets a flag when a match is found. The nonlocal declaration allows the inner function to modify the result variable defined in the outer scope.
def deeper(node):
if node:
nonlocal lookfor, result
if serialize(node) == lookfor:
result = True
return
deeper(node.left)
deeper(node.right)
The traversal is initiated with the original root node, and the final boolean outcome is returned:
deeper(root)
return result
Edge Cases Handled
When subRoot is None, the serializer returns an empty string, and the comparison against any subtree of root will succeed only if a corresponding empty representation is encountered, effectively treating an empty tree as a valid subtree of any tree.
When root itself is None, the deeper function immediately exits without invoking the serializer, leaving result as False, which correctly indicates that a non-empty subRoot cannot be found inside an empty tree.
The delimiter-rich serialization format distinguishes between nodes with identical values but different structures, such as a left-only child versus a right-only child, because the presence or absence of the l= and r= markers is encoded explicitly.
Performance Optimizations
The use of @cache on the serialize function eliminates repeated string construction for nodes that are visited multiple times during the depth-first search. Since each node’s serialized form is computed at most once, the overall work of building string representations scales with the number of distinct nodes rather than the number of comparison attempts.
The early-exit condition inside deeper-setting result to True and returning immediately-prevents unnecessary traversal of the remainder of the tree once a matching subtree has been identified. This short-circuiting reduces the amount of work in cases where the subtree appears near the top of root.
By keeping the serialized target (lookfor) as a single immutable string, the equality check serialize(node) == lookfor becomes a fast, constant-time operation for each node, relying on Python’s efficient string comparison implementation.
Overall, the combination of memoization, early termination, and concise string comparison yields a solution that avoids redundant computation while maintaining a clear recursive structure.
ELI5 - Simplified Explanation
Imagine a giant family tree where every person has a name and might have some branches attached to them. Sometimes, you want to see if a smaller group of people is hiding somewhere inside that big tree exactly as they are arranged.
The code starts by taking the small group and writing down a special secret code for them. It visits each person, writes down who is on their left side, then their own name, and then who is on their right side. By doing this for everyone in the small group, it creates a unique string of letters and symbols that represents that exact shape.
Next, the computer looks at the big tree. It goes to every single person in the big tree and pretends that they are the very top of their own little family. It writes down the secret code for that spot just like it did before. Then, it compares this code to the secret code from the small group. If the codes match, it means the small group is hiding right there.
The computer explores the entire big tree by checking every spot, going down the left side and the right side until it has seen everyone. If it finds a match, it remembers that it found what it was looking for. Once it finishes checking all the spots, it will be able to tell if that small group was tucked away somewhere inside the big structure.
Code Quality
Complexity Analysis
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++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | |||||||||
| leetcode.ca | C++ | Java | Rust | Python | JS | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| bujosa | Rust | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fsq | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | Python | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Java | ||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| bujosa | Rust | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fsq | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | Python | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 250: Count Univalue Subtrees
- problem 508: Most Frequent Subtree Sum
Solved On The Same Day
- problem 292: Nim Game
- problem 617: Merge Two Binary Trees
- problem 671: Second Minimum Node In a Binary Tree
- problem 152: Maximum Product Subarray
- problem 207: Course Schedule
- problem 210: Course Schedule II
- problem 211: Design Add and Search Words Data Structure
- problem 213: House Robber II
- problem 237: Delete Node in a Linked List
- problem 260: Single Number III
- problem 416: Partition Equal Subset Sum
- problem 437: Path Sum III
- problem 450: Delete Node in a BST
- problem 560: Subarray Sum Equals K
- problem 606: Construct String from Binary Tree
- problem 623: Add One Row to Tree
- problem 652: Find Duplicate Subtrees
- problem 654: Maximum Binary Tree
- problem 655: Print Binary Tree
- problem 662: Maximum Width of Binary Tree
- problem 669: Trim a Binary Search Tree
- problem 687: Longest Univalue Path
- problem 1115: Print FooBar Alternately
- problem 1116: Print Zero Even Odd
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