Sponsored
Sponsored
This approach involves performing an in-order traversal to visit the nodes of the tree in sorted order. As we visit each node, we rearrange the nodes to form a new tree where each node only has a right child.
We will use a dummy node that helps us easily chain the nodes in the desired manner. During the traversal, we append each node to the right of the previous node.
Time Complexity: O(n), where n is the number of nodes, as we visit each node once.
Space Complexity: O(n), due to the recursion stack space where n is the number of nodes.
1function TreeNode(val, left = null, right = null) {
2 this.val = (val===undefined ? 0 : val);
3 this.left = (left===undefined ? null : left);
4 this.right = (right===undefined ? null : right);
5}
6
7var increasingBST = function(root) {
8 let dummy = new TreeNode(0);
9 let cur = dummy;
10
11 function inorder(node) {
12 if (!node) return;
13 inorder(node.left);
14 node.left = null;
15 cur.right = node;
16 cur = node;
17 inorder(node.right);
18 }
19
20 inorder(root);
21 return dummy.right;
22};
The JavaScript solution uses a closure function inorder
to handle the traversal, allowing access to the cur
variable that tracks the end of our reordered list. The dummy node helps in easily returning the result without special cases.
A space-optimized approach to perform in-order traversal without recursion or a stack is Morris Traversal. This involves temporarily modifying the tree structure by linking the in-order predecessor of each node to the node itself, allowing us to traverse the tree without additional space.
During the traversal, we reconstruct the tree in the desired form by altering the left and right pointers.
Time Complexity: O(n), as each node is processed a constant number of times (at most twice).
Space Complexity: O(1), as we are not using any extra space other than a couple of pointers.
The Python solution employs Morris Traversal to achieve O(1) space complexity. We use a while
loop to traverse the tree while altering the pointers as described. When there's a left subtree, we find the predecessor, link it, and then follow the same logic until the tree is reconstructed in the desired order.