Subtree of Another Tree (LeetCode 572): Solution and Explanation

Easy
Tree
Depth First Search
String Matching
Binary Tree
Hash Function

You are given two binary trees, root and subRoot, and must decide whether subRoot appears inside root as a complete subtree. That means some node in root, together with all of its descendants, has exactly the same shape and values as subRoot.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A subtree is not just any matching chunk of nodes. If a node in root is chosen as the starting point, everything below it must match subRoot, down to the leaves. So the question reduces to two smaller ones: which node of root could be the starting point, and does the tree hanging from that node equal subRoot exactly?

The second question is the classic same-tree check: two trees are equal when their roots match and their left and right subtrees are recursively equal. The first question has no shortcut in general, because the match could start at any node. So the natural approach is to walk every node of root and run the same-tree check from there, stopping as soon as one succeeds.

This is brute force with good structure, and for the usual constraints (a few thousand nodes) it is fast enough, because most same-tree checks fail within a step or two when the root values differ. If you need guaranteed linear time, you can serialize both trees with null markers and run a string matching algorithm, but the nested recursion is what interviewers usually expect first.

Approach: DFS over root with a same-tree check at each node

  1. If subRoot is empty, return True, since an empty tree is a subtree of anything.
  2. If root is empty but subRoot is not, return False because there is nowhere left to match.
  3. Call isSameTree(root, subRoot). If the tree rooted at the current node equals subRoot, return True.
  4. Otherwise recurse into root.left and then root.right, returning True if either side contains subRoot.
  5. Inside isSameTree, return True when both nodes are None, False when exactly one is None or the values differ, and otherwise require both the left pair and right pair to match.

Step-by-step example

root = [3,4,5,1,2], subRoot = [4,1,2]
  1. At the root node 3, isSameTree(3, 4) fails immediately because 3 differs from 4.
  2. Recurse into the left child, node 4. Now isSameTree(4, 4) compares the roots, which match.
  3. It compares the left children 1 and 1, which match and both have no children, then the right children 2 and 2, which also match.
  4. The same-tree check returns True, so isSubtree at node 4 returns True, and the or at node 3 returns True without exploring node 5.
  5. If node 2 in root had an extra child 0, the check at node 4 would fail at that child, every other start would fail too, and the answer would be False.

Code: Python, Java, C++

1class Solution:
2    def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
3        if not subRoot: return True
4        if not root: return False
5        
6        if self.isSameTree(root, subRoot):
7            return True
8            
9        return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
10    
11    def isSameTree(self, p, q):
12        if not p and not q: return True
13        if not p or not q or p.val != q.val: return False
14        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

Time and space complexity

Time

O(m × n)

There are m nodes in root that can serve as a starting point, and each same-tree check may examine up to n nodes of subRoot before finishing. In practice most checks stop early on the first value mismatch.

Space

O(h)

The recursion depth is bounded by the height of root plus the height of subRoot, so the stack uses space proportional to tree height rather than node count.

Other approaches

Serialize and string match (time O(m + n), space O(m + n))

Serialize both trees in preorder with explicit null markers and separators around each value, then check whether the subRoot string occurs in the root string using KMP or a similar linear matcher. The separators prevent a value like 2 from matching inside 12.

Merkle-style subtree hashing (time O(m + n), space O(m))

Compute a hash for every subtree bottom up from its value and its children's hashes, then look for a node whose hash equals the hash of subRoot, confirming with a same-tree check to rule out collisions.

Common mistakes

  • Returning the result of isSameTree at the root directly instead of falling through to the children when it is False.
  • Treating a partial match as a subtree. The descendants of the matched node must line up all the way to the leaves, which is why a full same-tree check is required.
  • Serializing without null markers or without delimiters, which lets different trees or different numbers produce false string matches.
  • Mixing up the arguments and checking whether root is a subtree of subRoot in the recursive calls.

Frequently asked questions

What is the time complexity of Subtree of Another Tree?

The straightforward recursive solution is O(m × n) in the worst case, where m and n are the node counts of the two trees. It runs a same-tree comparison from each node of the larger tree.

Can Subtree of Another Tree be solved in linear time?

Yes. Serialize both trees with null markers and delimiters, then use KMP or the Z algorithm to search for the smaller string inside the larger one. Subtree hashing is another linear-time option.

What is the difference between a subtree and a matching subgraph?

A subtree must include a node and every one of its descendants. You cannot stop partway down, so if the candidate node in root has an extra child that subRoot does not have, it is not a match.