Given the root of a binary tree, mirror it by swapping the left and right children of every node. Return the root of the mirrored tree.
Tree Encoding
Your function receives root as a TreeNode (or the empty tree, as null) and returns the root of the mirrored tree. The node type is provided for you, with val, left and right fields; you may mirror in place and return the same root.
The examples below write trees as their level-order traversal, where null marks a missing child of a listed node and trailing nulls are omitted. That is only how trees are displayed; the encoding and decoding are done for you.
Constraints
The number of nodes in the tree is in the range [0,100].
−100≤Node.val≤100
Examples
Example 1
Input
root = [4, 2, 7, 1, 3, 6, 9]
root
Output
[4, 7, 2, 9, 6, 3, 1]
Explanation
The children of every node are swapped: 2 and 7 trade places under the root, 1 and 3 trade places under 2, and 6 and 9 under 7.
Example 2
Input
root = [2, 1, 3]
root
Output
[2, 3, 1]
Example 3
Input
root = []
Output
[]
Explanation
The empty tree mirrors to itself.
Loading editor...
Log in to run your code. Your draft is saved in this browser.Log inSign up