Subtree of Another Tree
Difficulty: Easy · Pattern: Trees & BST · LeetCode #572
Given the roots of two binary trees root and subRoot, return true if some node of root has a subtree that is identical to subRoot, in structure and in values. The subtree of a node includes that node and all of its descendants.
Examples
root = [3,4,5,1,2], subRoot = [4,1,2] → true
root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2] → false (node 2 has an extra child 0)Hints
- Reuse Same Tree: is the tree rooted at the current node identical to
subRoot? - If not, try the left subtree and the right subtree.
Approach
Brute force (accepted): walk every node of root and call same(node, subRoot). In the worst case that's O(m·n).
Linear alternative: serialize both trees with null markers and value delimiters (e.g. ,3,4,#,#,5,#,#), then check whether one string contains the other using KMP. The delimiters matter: without them, 2 would wrongly match inside 12.
The brute force is what interviewers expect first. Mention the serialization trick as the optimization.
Complexity
Time: O(m·n) worst case (O(m+n) with serialization + KMP). Space: O(h).
Python solution
def isSubtree(root, subRoot):
def same(a, b):
if not a and not b:
return True
if not a or not b or a.val != b.val:
return False
return same(a.left, b.left) and same(a.right, b.right)
if not subRoot:
return True
if not root:
return False
return same(root, subRoot) or isSubtree(root.left, subRoot) or isSubtree(root.right, subRoot)JavaScript solution
function isSubtree(root, subRoot) {
const same = (a, b) => {
if (!a && !b) return true;
if (!a || !b || a.val !== b.val) return false;
return same(a.left, b.left) && same(a.right, b.right);
};
if (!subRoot) return true;
if (!root) return false;
return same(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}