LeetCode #572 Easy

Subtree of Another Tree

Subtree of Another Tree is LeetCode 572 (Easy). Given the roots of two binary trees, root and subRoot, return true if some node of root is the top of a copy of subRoot, and false otherwise.

  • A copy means the same values in the same shape: that node and all of its descendants.
  • The whole of root counts as one of its own subtrees.

root has at most 2,000 nodes and subRoot at most 1,000, so a full comparison from every node is fast enough.

Constraints
  • The number of nodes in the root tree is in the range [1, 2000].
  • The number of nodes in the subRoot tree is in the range [1, 1000].
  • -10^4 <= root.val <= 10^4
  • -10^4 <= subRoot.val <= 10^4
binary treedfsrecursion
Open on LeetCode ↗
02

Intuition

Split the question in two.

  • Is the tree starting at this node identical to subRoot? Compare the top values, then the left children with each other and the right children with each other, all the way down. An empty spot only matches an empty spot.
  • Which node do we test? The copy could start at any node of root, so try them all from the top down and stop at the first full match.

A node whose value equals subRoot's top is only a candidate. The copy can still fail deeper down, and a later node with the same value may be the real match.

How to spot this pattern

"Does one tree appear inside another" is a search wrapped around an equality check: one recursion picks the starting node, a second walks two trees side by side. Same Tree and Merge Two Binary Trees use that same paired walk.

03

Approach

Try it first

Before reading on, write a function that says whether two trees are identical, including what happens when one side is empty. Then decide which nodes of root you must try it on, and when you can stop. Aim for O(m · n).

1

Compare two trees node by node

same(a, b) is the Same Tree check (LeetCode 100). It returns true when both are empty, false when only one is empty or the values differ, and otherwise same(a.left, b.left) and same(a.right, b.right).

2

Try every node of root as the top

search(node) calls same(node, subRoot) and returns true on a match. Otherwise it tries search(node.left) or search(node.right), because the copy may start anywhere below this node.

3

Return false when the nodes run out

search(None) returns false. If every node fails, the or chain falls through to false, which means subRoot appears nowhere in root. The or also stops early: once the left side finds a copy, the right side is never searched.

4

Why this is correct

A subtree is a node plus everything under it, so any copy must begin at some node of root. The search tries every node, and same accepts only identical trees, so the answer is true exactly when a copy exists.

04

Code in Python, C++ and Java

▶1import sys
▶2 
▶3sys.setrecursionlimit(10000)
▶4 
▶5 
▶6class Solution:
▶7 def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
▶8 def same(a, b):
▶9 if not a and not b:
▶10 return True
▶11 if not a or not b or a.val != b.val:
▶12 return False
▶13 return same(a.left, b.left) and same(a.right, b.right)
▶14 
▶15 def search(node):
▶16 if not node:
▶17 return False
▶18 if same(node, subRoot):
▶19 return True
▶20 return search(node.left) or search(node.right)
▶21 
▶22 return search(root)
rootsubRoot34512412tops tried, top-down34125try 3 as the top: 3 is not 4 → no
a.val3
b.val4
Start the comparison at root's node 3. It already differs from subRoot's top value 4, so this node cannot be the top of a copy. The search moves on to the next node.
rootsubRoot34512412tops tried, top-down34125try 4 as the top: matches → compare below
a.val4
b.val4
Root's node 4 has the same value as subRoot's top, so it might be the top of a copy. Now every node below it must match subRoot node for node.
rootsubRoot34512412tops tried, top-down341251 matches 1, both are leaves
a.val1
b.val1
1 matches 1 in the same spot. Neither has children, so both empty pairs below match too and this branch is identical.
rootsubRoot34512412tops tried, top-down341252 matches 2, both are leaves
a.val2
b.val2
2 matches 2 in the same spot. Neither has children, so both empty pairs below match too and this branch is identical.
rootsubRoot34512412tops tried, top-down34125every node matched → true
returnTrue
Every node of subRoot has an equal partner under root's node 4, and the empty spots line up too. That is a full copy, so the answer is true and no other node needs trying.
05

Serialize and match

Preorder with a marker for every missing child writes each tree as a list that pins down its shape. A subtree's list is always one unbroken stretch of the big tree's list, so the problem becomes finding one list inside another. KMP does that in O(m + n), even when every value is the same.

▶1class Solution:
▶2 def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
▶3 def serialize(node):
▶4 out, stack = [], [node]
▶5 while stack:
▶6 cur = stack.pop()
▶7 if cur is None:
▶8 out.append(None)
▶9 else:
▶10 out.append(cur.val)
▶11 stack.append(cur.right)
▶12 stack.append(cur.left)
▶13 return out
▶14 
▶15 text, pat = serialize(root), serialize(subRoot)
▶16 fail = [0] * len(pat)
▶17 k = 0
▶18 for i in range(1, len(pat)):
▶19 while k and pat[i] != pat[k]:
▶20 k = fail[k - 1]
▶21 if pat[i] == pat[k]:
▶22 k += 1
▶23 fail[i] = k
▶24 
▶25 k = 0
▶26 for x in text:
▶27 while k and x != pat[k]:
▶28 k = fail[k - 1]
▶29 if x == pat[k]:
▶30 k += 1
▶31 if k == len(pat):
▶32 return True
▶33 return False
06

Common pitfalls

Stopping at the first node with the right value

✗ Wrong
if node.val == subRoot.val:
    return same(node, subRoot)
✓ Right
if same(node, subRoot):
    return True
return search(node.left) or search(node.right)

On root [4,4,null,1,2] and subRoot [4,1,2], the top 4 fails the comparison and the function returns false. The 4 just below it is a copy, so the answer is true.

Letting an empty side count as a match

✗ Wrong
if not a or not b:
    return True
✓ Right
if not a and not b:
    return True
if not a or not b:
    return False

Only empty against empty is a match. On root [3,4,5,1,2,null,null,null,null,0] and subRoot [4,1,2], the extra 0 under 2 is ignored and the answer comes out true instead of false.

Serializing without markers for empty children

✗ Wrong
out.append(cur.val)  # nothing for a missing child
✓ Right
out.append(None)  # once for every missing child

Root [1,2] and subRoot [1,null,2] both become 1, 2, so the list search says true. With markers they are 1, 2, #, #, # and 1, #, 2, #, #, which differ. Gluing values into one string adds a second trap: "12" contains "2".

07

Edge cases

A 2,000-node chain

The search goes 2,000 calls deep and the comparison adds up to 1,000 more, past Python's default limit of 1,000, so the code raises it with sys.setrecursionlimit. The serialization version uses an explicit stack and needs no limit.

08

Complexity

Time
O(m · n)
Space
O(H + h)
m and n are the node counts of root and subRoot; H and h are their heights. same can run n steps from each of the m nodes, which happens when many values repeat, such as two trees of all 1s. Usually a comparison fails within a node or two. The stack holds one search call per level of root plus one comparison call per level of subRoot.
09

Subtree of Another Tree FAQ

Can hashing make the check faster?

Give every node a hash built from its value and its children's hashes, computed bottom-up. Identical subtrees get identical hashes, so compare subRoot's hash with each node's and confirm any hit with same, in case two different trees collide. That runs in O(m + n) on average.

What is the difference between a subtree and a substructure?

A subtree must include every descendant of its top node, which is what this problem asks. A substructure only needs subRoot's nodes to appear, so extra children in root are allowed, and the comparison returns true as soon as subRoot runs out.