#K47937. Check for Mirror Binary Trees
Check for Mirror Binary Trees
Check for Mirror Binary Trees
Given two binary trees, determine whether they are mirror images of each other. Two binary trees are mirrors if the left subtree of one tree is the mirror of the right subtree of the other tree and vice versa.
The trees are described by a list of node triples. Each triple contains three integers: the value of the parent node, its left child, and its right child. A child value of -1 indicates that there is no corresponding child.
The mirror condition can be expressed in LaTeX as:
$$\text{isMirror}(t_1, t_2) = \begin{cases}\text{True} & \text{if } t_1 = t_2 = \text{NULL}\\ \text{False} & \text{if } t_1 = \text{NULL} \text{ or } t_2 = \text{NULL}\\ \text{isMirror}(t_1.left, t_2.right) \wedge \text{isMirror}(t_1.right, t_2.left) & \text{otherwise}\end{cases}$$Your task is to construct the two binary trees from the input and determine if they are mirrors of each other.
inputFormat
The input is given via standard input (stdin) and has the following format:
<n> <parent> <left> <right> ... (n lines for the first tree) <m> <parent> <left> <right> ... (m lines for the second tree)
Here, n
and m
are the number of nodes in the first and second trees respectively. Each of the following lines provides three space-separated integers representing a node and its children. A value of -1
indicates that a child does not exist.
outputFormat
Output a single line to standard output (stdout) containing YES
if the two binary trees are mirrors of each other, or NO
otherwise.
6
1 2 3
2 4 5
3 -1 -1
4 -1 -1
5 -1 -1
-1 -1 -1
6
1 3 2
3 -1 -1
2 5 4
5 -1 -1
4 -1 -1
-1 -1 -1
YES