All problems

Problem 407

Subtree of Another Tree

Easy · 10 pts · Tree, Depth-First Search, Binary Tree

Problem

Decide whether the second tree is a subtree of the first. A subtree of a tree T is a node of T together with all of its descendants, so it must match all the way down to the leaves: the same structure and the same values. A tree is also considered a subtree of itself. Check every node of the first tree as a possible starting point.

Input

The first tree, then the second tree, each as two lines: the token count N and the N level-order tokens ('null' for missing children).

Output

Print YES if the second tree is a subtree of the first, otherwise NO.

Constraints

1 <= number of nodes in each tree <= 1000; -10000 <= value <= 10000

Example input

5
3 4 5 1 2
3
4 1 2

Example output

YES

Explanation

The first tree 3 / 4 5 / 1 2 contains the node 4 with children 1 and 2, which is exactly the second tree, so the answer is YES.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Maximum Level Sum Next: Merge Two Binary Trees