Practice › Trees
Subtree of Another Tree
Easy · Trees · Asked at Amazon, Microsoft, Meta, Google
Print YES if tree B is a subtree of tree A — that is, some node of A together with all of its descendants is identical to B (same shape and same values). Otherwise print NO.
Input
Tree A, then tree B, each as two lines: k, then k values in level order (-1 means no node).
Output
YES or NO.
Constraints
- 1 ≤ nodes in A ≤ 2000
- 1 ≤ nodes in B ≤ 1000
- values are positive
For every node of A, check whether the tree rooted there is identical to B (both null, or same value and identical children). O(|A| × |B|) is fine here; serialising both trees and searching for one string in the other is faster.
Example 1
Input
5 3 4 5 1 2 3 4 1 2
Output
YES
Example 2
Input
10 3 4 5 1 2 -1 -1 -1 -1 7 3 4 1 2
Output
NO
Hints
- If B is a subtree of A, its root matches some node of A.
- Write a helper that checks whether two trees are identical.
- Try it from every node of A.
Approach
identical(x, y) is true when both are null, or both exist with equal values and identical left and right children. Visit every node of A and stop at the first one where identical(node, B) holds. With |A| ≤ 2000 and |B| ≤ 1000 the O(|A| · |B|) worst case is fast enough. (For huge trees, serialise both with null markers and use string matching.)
Complexity: O(|A| · |B|) time · O(|A| + |B|) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
long long val;
Node *left = nullptr, *right = nullptr;
Node(long long v) : val(v) {}
};
// level order with -1 for a missing child
Node *build(const vector<long long> &a) {
if (a.empty() || a[0] == -1) return nullptr;
Node *root = new Node(a[0]);
queue<Node *> q;
q.push(root);
size_t i = 1;
while (!q.empty() && i < a.size()) {
Node *cur = q.front();
q.pop();
if (i < a.size() && a[i] != -1) q.push(cur->left = new Node(a[i]));
i++;
if (i < a.size() && a[i] != -1) q.push(cur->right = new Node(a[i]));
i++;
}
return root;
}
vector<long long> readTree() {
int k;
cin >> k;
vector<long long> a(k);
for (auto &x : a) cin >> x;
return a;
}
bool identical(Node *x, Node *y) {
if (!x || !y) return x == y;
return x->val == y->val && identical(x->left, y->left) && identical(x->right, y->right);
}
int main() {
Node *A = build(readTree());
Node *B = build(readTree());
vector<Node *> st = {A};
while (!st.empty()) {
Node *n = st.back();
st.pop_back();
if (identical(n, B)) {
cout << "YES\n";
return 0;
}
if (n->left) st.push_back(n->left);
if (n->right) st.push_back(n->right);
}
cout << "NO\n";
return 0;
}Python solution
import sys
from collections import deque
class Node:
__slots__ = ("val", "left", "right")
def __init__(self, val):
self.val, self.left, self.right = val, None, None
def build(a):
"""Level order with -1 for a missing child."""
if not a or a[0] == -1:
return None
root = Node(a[0])
q = deque([root])
i = 1
while q and i < len(a):
cur = q.popleft()
if i < len(a) and a[i] != -1:
cur.left = Node(a[i])
q.append(cur.left)
i += 1
if i < len(a) and a[i] != -1:
cur.right = Node(a[i])
q.append(cur.right)
i += 1
return root
def identical(x, y):
stack = [(x, y)]
while stack:
a, b = stack.pop()
if a is None or b is None:
if a is not b:
return False
continue
if a.val != b.val:
return False
stack.append((a.left, b.left))
stack.append((a.right, b.right))
return True
data = list(map(int, sys.stdin.read().split()))
k1 = data[0]
A = build(data[1 : 1 + k1])
k2 = data[1 + k1]
B = build(data[2 + k1 : 2 + k1 + k2])
stack = [A]
found = False
while stack and not found:
node = stack.pop()
if identical(node, B):
found = True
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
print("YES" if found else "NO")Java solution
import java.io.*;
import java.util.*;
public class Main {
static class Node {
long val;
Node left, right;
Node(long v) { val = v; }
}
// level order with -1 for a missing child
static Node build(long[] a) {
if (a.length == 0 || a[0] == -1) return null;
Node root = new Node(a[0]);
ArrayDeque<Node> q = new ArrayDeque<>();
q.add(root);
int i = 1;
while (!q.isEmpty() && i < a.length) {
Node cur = q.poll();
if (i < a.length && a[i] != -1) q.add(cur.left = new Node(a[i]));
i++;
if (i < a.length && a[i] != -1) q.add(cur.right = new Node(a[i]));
i++;
}
return root;
}
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static long next() throws IOException {
in.nextToken();
return (long) in.nval;
}
static long[] readTree() throws IOException {
int k = (int) next();
long[] a = new long[k];
for (int i = 0; i < k; i++) a[i] = next();
return a;
}
static boolean identical(Node x, Node y) {
if (x == null || y == null) return x == y;
return x.val == y.val && identical(x.left, y.left) && identical(x.right, y.right);
}
public static void main(String[] args) throws IOException {
Node A = build(readTree());
Node B = build(readTree());
ArrayDeque<Node> st = new ArrayDeque<>();
st.push(A);
while (!st.isEmpty()) {
Node n = st.pop();
if (identical(n, B)) {
System.out.println("YES");
return;
}
if (n.left != null) st.push(n.left);
if (n.right != null) st.push(n.right);
}
System.out.println("NO");
}
}Solve Subtree of Another Tree online · All practice problems