Problem 572

Abstract / Summary

Check if one tree is a subtree of another by seeing if a part of the larger tree matches the smaller tree's structure and node values exactly.

Note

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

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
24 lines | 715 bytes | submitted September 4, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
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 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.

written by openai gpt

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.

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 = 6 | μ = 5.92 | σ = 1.57

Complexity Analysis

not analyzed yet

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++ 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++
46 links | 31 authors | 10 languages

Videos

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

Similar Problems

2 similar problems

Solved On The Same Day

3 easy 21 medium
25 solutions   September 4, 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