Mirror a Binary Tree
Problem statement
Given the root of a binary tree, reflect it from left to right: at every node, the left subtree and the right subtree trade places. Return the root of the mirrored tree.
You may change the given tree in place or build a new one. Write it both recursively and without recursion.
Function
mirrorTree(root: TreeNode) → TreeNodeExamples
Example 1
root = [8,3,10,1,6,null,14]return = [8,10,3,14,null,6,1]At the root, 3 and 10 trade places. Under 10, the right child 14 becomes the left child. Under 3, 1 and 6 trade places. Read level by level, the result is [8, 10, 3, 14, null, 6, 1].
Example 2
root = [1,2,null,3]return = [1,null,2,null,3]A chain going left (1, then 2, then 3) becomes a chain going right.
Example 3
root = [5]return = [5]A single node is its own mirror.
Constraints
- The tree has between
1and500nodes. -1000 <= node.val <= 1000- The tree does not have to be balanced. It can be a single chain of
500nodes.