Problem Description
Given the root of a binary tree, transform the tree by turning it upside down. In this transformation, every original left child becomes the new root, the original root becomes the new right child, and the original right child becomes the new left child. The transformation is applied level by level and it is guaranteed that every right node has a sibling and no children.
Key Insights
- The transformation is easier to perform using recursion, processing from the bottom-most left child up.
- The base case is when the current node is null or when it doesn’t have a left child.
- As the recursion unwinds, reassign pointers: the left child’s left becomes the original right, and the left child’s right becomes the current node.
- After reassignments, remove the original left and right pointers to avoid cycles.
- The new root is determined by the left-most node in the original tree.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes, since every node is visited once. Space Complexity: O(h), where h is the height of the tree, due to the recursion stack.
Solution
We use a recursive approach to flip the tree. We start by recursively reaching the left-most node, which will ultimately be the new root. As we return from recursion, we perform the following steps for the current node:
- Set the left child’s left pointer to the original right child.
- Set the left child’s right pointer to the current node.
- Nullify the current node’s left and right pointers to break old connections. This method ensures that each level of the tree is correctly transformed, resulting in the upside-down binary tree.