All problems

Problem 602

Leaf-Similar Trees

Easy · 10 pts · Tree, Depth-First Search

Problem

The leaf value sequence of a binary tree lists the values of its leaves (nodes with no children) from left to right. Two trees are leaf-similar if their leaf value sequences are exactly the same, even if the trees have different shapes. Given two binary trees, decide whether they are leaf-similar. Collect the leaves of each tree with a depth-first search that visits left children before right ones, then compare the two lists.

Input

The input describes two trees, one after the other. Each tree is given as a line with N, the number of tokens, followed by a line with N level-order tokens, where 'null' marks a missing child.

Output

Print YES if the trees are leaf-similar, otherwise NO.

Constraints

1 <= number of nodes in each tree <= 200; 0 <= value <= 200

Example input

11
3 5 1 6 2 9 8 null null 7 4
15
3 5 1 6 7 4 2 null null null null null null 9 8

Example output

YES

Explanation

The tree 3 5 1 6 2 9 8 null null 7 4 has leaves 6 7 4 9 8 from left to right. The second tree has the same leaf sequence, so the answer is YES.

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

Previous: Sum of Nodes with Even-Valued Grandparent Next: Univalued Binary Tree