Problem 612
Flip Equivalent Binary Trees
Medium · 20 pts · Tree, Depth-First Search
Problem
A flip operation chooses any node and swaps its left and right subtrees. Two binary trees are flip equivalent if one can be turned into the other by some number of flips. Given two trees, decide whether they are flip equivalent. Recursively, two nodes match if their values are equal and their children match either directly (left with left, right with right) or crosswise (left with right, right with left).
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 flip equivalent, otherwise NO.
Constraints
1 <= number of nodes in each tree <= 100; 0 <= value <= 99; values within each tree are distinct
Example input
11 1 2 3 4 5 6 null null null 7 8 13 1 3 2 null 6 4 5 null null null null 8 7
Example output
YES
Explanation
Flipping the nodes 1, 3 and 5 of the first tree 1 2 3 4 5 6 null null null 7 8 turns it into the second tree. So the trees are flip equivalent and the answer is YES.