2 versions of this question:
- Given a binary tree, return the mirror of it.
Very easy. Recursion
TreeNode mirror(TreeNode root) {
if (root == NULL)
return NULL;
else {
TreeNode newNode = new TreeNode(root.val);
newNode->left = mirror(root->right);
newNode->right = mirror(root->left);
return newNode;
}
}
- Find whether a given binary tree is mirror image of the other one.
recursion
public boolean isMirrorImage(Node root1, Node root2) {
if (root1 == null && root2 == null) {
return true;
}
if (root1 != null && root2 != null && root1.val == root2.val) {
return isMirrorImage(root1.left, root2.right) && isMirrorImage(root1.right, root2.left);
}
return false;
}
Solution 2, using in-order traversal, put them into a queue. Use queue1 to store left children in order of left to right and queue2 to store right children in order of right to left and compare for equality.