Mirror Tree
Given a binary tree, convert it into its mirror image and return the root of the mirrored tree. The mirror of a tree is achieved by swapping the left and right children of all nodes in the tree. You may modify the original tree and return it or create a new one.
[ [ 1, 2, 3, 4, 5 ] ]
Explanation. The original tree structured as `[1, 2, 3, 4, 5]` where 1 is the root, 2 is its left child, 3 is its right child, 4 is the left child of 2, and 5 is the right child of 2. Mirroring it swaps all left and right children, resulting in `[1, 3, 2, 5, 4]`.
[ [ 4, 2, 7, 1, 3, 6, 9 ] ]
Explanation. Swapping every left and right child nodes transforms the tree `[4, 2, 7, 1, 3, 6, 9]` to `[4, 7, 2, 9, 6, 3, 1]`.
[ [ 2, 3, 1 ] ]
Explanation. Mirror image of tree `[2, 3, 1]` results in `[2, 1, 3]` where node 3 and 1 are swapped.
[ [ 1 ] ]
Explanation. Mirroring a single node tree results in the same tree `[1]`.
[ [ 1, null, 2, null, 3 ] ]
Explanation. Original tree is `[1, null, 2, null, 3]` with nodes increasing to the right. After mirroring, the nodes accumulate to the left resulting in `[1, 2, null, 3]`.
Follow-up: How would you solve the problem iteratively?
Assume the tree has at most 100 nodes. Each node's value is a non-negative integer.
- Views
- 3