Binary Tree Upside Down
Trees
MediumLeetCode #156
Problem Statement
Given the `root` of a binary tree, turn the tree upside down and return the new root. You can assume that every right node has a sibling (a left node with the same parent) and has no children.
Example
Original
Upside Down
Algorithm Explanation
We can solve this problem recursively. The main idea is to traverse to the leftmost node, which will become the new root. Then, as we backtrack, we rearrange the pointers.
Algorithm Steps
- Base Case: If the current node is null or a leaf, we return it as it is.
- Recursive Call: Recursively call the function on the left child. This will return the new root of the upside-down tree.
- Rearrange Pointers: Once the recursive call returns, we are at a parent node. We set its left child's left pointer to the parent's right child, and the left child's right pointer to the parent itself.
- Clear Old Pointers: After rearranging, we set the original parent's left and right pointers to null to avoid cycles.
Start
Starting the process.
Binary Tree Upside Down Solution