Problem Description
Given the root of a binary tree and a target leaf node, change the root of the tree so that the given leaf becomes the new root. The rerooting must be done according to the following rules for every node cur on the path from the leaf (inclusive) up to but not including the original root:
- If cur has a left child, then that left child becomes cur’s right child.
- cur’s original parent becomes cur’s left child. All corresponding parent pointers must be updated correctly.
Key Insights
- The transformation only affects the chain of nodes on the path from the given leaf up to the original root.
- At each step, we “reverse” the pointer between the current node and its parent.
- If the current node originally had a left child (which might not be part of the chain), it must be moved to become its right child.
- It is important to detach the link from the parent to the current node so that, after the rerooting, each node (aside from the new root) has only one parent.
- Care must be taken to update all parent pointers so that the final tree is consistent.
Space and Time Complexity
Time Complexity: O(H) where H is the height of the tree. In the worst-case (skewed tree), H = O(N). Space Complexity: O(1) extra space if using an iterative approach (ignoring recursion stack) or O(H) if recursion is used.
Solution
We solve the problem by “reversing” the pointers along the chain from the given leaf to the original root. First, we keep a reference to the new root (the given leaf). Then, for the current node cur, while its parent exists, we do the following:
- Save the current left child (if any) so that it can be used to update the right child.
- If the current node has a left child, move it to be the right child.
- Make the original parent of cur become its left child.
- Detach cur from its original parent by nulling out the parent's pointer to cur.
- Update the parent pointer of the original parent so that it now points back to cur.
- Move cur up to its parent (which has now become a child of the previous cur) and continue. After the loop ends the given leaf remains our new root; just ensure its parent pointer is set to null.
This method uses an iterative approach with constant extra space. The crux is careful pointer manipulation based on the instructions, essentially “reversing” the singly–linked chain stored in the parent pointers while preserving the non-chain left child (by reassigning it to the right child).