Problem Description
Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node becomes the new root. Every node in the new tree should have no left child and only one right child.
Key Insights
- Use in-order traversal to access nodes in ascending order.
- As you visit each node, adjust pointers: remove the left child and attach the node as the right child of the previously processed node.
- Using a dummy node simplifies the process by providing a fixed starting point for the new tree structure.
- Recursive in-order traversal is straightforward and leverages the inherent properties of a BST.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes in the tree. Space Complexity: O(n) in the worst-case scenario due to recursion stack and the additional space used for the new tree structure.
Solution
Perform an in-order traversal to visit the nodes in ascending order. Use a dummy node to initiate the new tree and maintain a pointer (current) to the most recent node added. For each visited node, set the left pointer to null and attach it as the right child of current. This approach rearranges the tree in one pass without the need for additional complex data structures.