456. Mirror Image Tree

A graphic designer has a binary tree sketch rooted at root and wants its reflection in a vertical mirror: at every node the left and right subtrees trade places, all the way down, while each node keeps its value.

Return the root of the reflected tree. The tree may be modified in place or rebuilt. If root is empty, return an empty tree. The result is compared by its level-order listing, with null for missing children.

Example 1

Input:
root = [2,7,5,null,3,8]
Output:
[2,5,7,null,8,3]
Explanation:

Swapping children at every node moves 5 (with child 8) to the left and 7 (with child 3) to the right, giving [2,5,7,None,8,3].

Example 2

Input:
root = [9,1]
Output:
[9,null,1]
Explanation:

The single left child 1 becomes the right child: [9,null,1].

Constraints

0 ≤ number of nodes ≤ 105

-1000 ≤ node value ≤ 1000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(h)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…