Subtree of Another Tree
Easy
Topics
Given the roots of two binary trees root and subRoot, return true if subRoot appears as a subtree of root (a node of root plus all its descendants matches subRoot exactly).
Example 1
root
subRoot
The shaded part of the first tree matches the second exactly, all the way down to its leaves — a partial match at the top does not count. So the answer is
true.Tree given in level-order (breadth-first);
null marks a missing child.Input: root = [3,4,5,1,2], subRoot = [4,1,2] Output: true
Example 2
root
subRoot
Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2] Output: false
Constraints
- 1 <= root nodes <= 2000
- 1 <= subRoot nodes <= 1000
- -10^4 <= Node.val <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
At every node of the big tree, ask "is the subtree rooted here identical to subRoot?" That inner check is just the Same Tree comparison.
Approach
- Write a
sameTree(a, b)helper. - Traverse root; at each node test
sameTree(node, subRoot). - Return true if any node matches.
Dry Run
root = 3 4 5 1 2 subRoot = 4 1 2
3 4
/ \ / \
4 5 1 2
/ \
1 2
The outer walk asks the same question at every node, and the inner `same` answers
it:
same(node 3, subRoot) 3 != 4, fails on the very first comparison -> false
same(node 4, subRoot) 4 == 4, then 1 == 1, then 2 == 2 -> true
answer true, found at the second node tested
That is where the O(m * n) comes from, and the trace shows both halves of it. Most
calls to `same` die on the root comparison and cost O(1); the one that matches
walks all of subRoot. In the worst case -- a big tree whose every node has the same
value as subRoot's root -- every one of the m calls walks all n nodes.
The near-miss is worth running too. Add a single 0 beneath the 2, so root becomes
3 4 5 1 2 null null null null 0, and the answer flips to false. `same` requires
structural identity, not containment: the node 4 now has an extra descendant that
subRoot does not, so matching values down to subRoot's leaves is not enough.
`if not q: return True` has to come before `if not p`. An empty subRoot is a
subtree of anything, including an empty tree, and testing p first would return
false for that pair.Complexity
- Time — O(m*n): each of m nodes may trigger an O(n) comparison.
- Space — O(h): recursion stack.
Common Pitfalls
- An empty subRoot is a subtree of anything; handle it before dereferencing.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSubtree(self, p, q):
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 q: return True
if not p: return False
if same(p,q): return True
return self.isSubtree(p.left,q) or self.isSubtree(p.right,q)import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public boolean isSubtree(TreeNode p, TreeNode q) {
if(q==null)return true;
if(p==null)return false;
if(same(p,q))return true;
return isSubtree(p.left,q)||isSubtree(p.right,q);
}
boolean same(TreeNode a,TreeNode b) {
if(a==null&&b==null)return true;
if(a==null||b==null||a.val!=b.val)return false;
return same(a.left,b.left)&&same(a.right,b.right);
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: bool isSubtree(TreeNode* p, TreeNode* q) {
function<bool(TreeNode*,TreeNode*)> same=[&](TreeNode* a,TreeNode* b)->bool {
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(!q)return true;
if(!p)return false;
if(same(p,q))return true;
return isSubtree(p->left,q)||isSubtree(p->right,q);
}
};/** Tree node shape: { val, left, right } */ /**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/ var isSubtree = function(p, q) {
function 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(!q)return true;
if(!p)return false;
if(same(p,q))return true;
return isSubtree(p.left,q)||isSubtree(p.right,q);
};
Asked at
eBay