Problem
Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
Examples
Example 1
| |
Example 2
| |
Constraints
- The number of nodes in the given tree will be in the range
[1, 100]. 0 <= Node.val <= 1000
Solution
Method 1 – Inorder Traversal with Re-linking
Intuition
The in-order traversal of a BST yields nodes in increasing order. By visiting nodes in-order and re-linking them so each node has no left child and only a right child, we can build the required tree.
Approach
- Perform an in-order traversal of the BST.
- For each visited node:
- Set its left child to null.
- Link it as the right child of the previously visited node.
- Use a dummy node to simplify linking.
- Return the right child of the dummy node as the new root.
Code
| |
| |
| |
| |
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(n)— Each node is visited once during in-order traversal. - 🧺 Space complexity:
O(h)— Call stack for recursion, where h is the height of the tree.