Skip to main content

Mirror a Binary Tree

EasyTreesDfs113 tests

You are given root, the root of a binary tree.

Turn the tree into its mirror image: for every node, swap its left child and its right child. Return the root of the mirrored tree.

After the change, the tree looks like the original seen in a mirror: what was on the left of any node is now on its right, at every level.

How the input is shown

A tree is shown as a list in level order: the root first, then each level from left to right. null marks a missing child, and missing children of a missing node are not listed. For example, [4, 2, 7, null, 3] is root 4 with left child 2 and right child 7, and 2 has only a right child, 3. An empty tree is []. Your returned tree is shown in the same way.

Note

  • If the tree is empty, return null.
  • Hint: swapping the two children of the root is not enough. Swap them, then do the same for the left subtree and for the right subtree. A short recursive function does this; a queue of nodes to visit works too.

Examples

Example 1

Input:
[5,3,8,1,4,null,9]
Output:
[5,8,3,9,null,4,1]

The children of 5 swap: 8 is now on the left and 3 on the right. Under 8, the 9 moves from the right to the left. Under 3, the children 1 and 4 swap places.

Example 2

Input:
[2,7]
Output:
[2,null,7]

7 was the left child of 2. In the mirror it is the right child, so the left place is shown as null.

Example 3

Input:
[]
Output:
[]

An empty tree is its own mirror.

Constraints

  • 0 <= number of nodes <= 60
  • -100 <= Node.val <= 100

Run checks your code against the 3 examples. Submit checks it against all 113 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.