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
rootcounts 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.
- 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
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.
"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.
Approach
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).
Two ways to solve it
Run the Same Tree check from each node of root.
- Short: two small recursive functions.
- Fast in practice: most tries fail at the first node.
The usual interview answer.
Write both trees in preorder with a marker for every empty child, then find subRoot's list inside root's with KMP.
- Linear: even when every value is equal.
- Cost: more code, and the markers are easy to forget.
The follow-up when asked to beat O(m · n).
With at most 2,000 and 1,000 nodes, both pass easily. Trying every node is shorter, so the steps, code and demo use it; the serialization version comes after the demo.
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).
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.
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.
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.
Code in Python, C++ and Java
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.
Common pitfalls
Stopping at the first node with the right value
if node.val == subRoot.val:
return same(node, subRoot)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
if not a or not b:
return Trueif not a and not b:
return True
if not a or not b:
return FalseOnly 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
out.append(cur.val) # nothing for a missing child
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".
Edge cases
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.
Complexity
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.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.