897. Increasing Order Search Tree

Explanation

To solve this problem, we can perform an in-order traversal of the given binary search tree. During the traversal, we construct a new tree by rearranging the nodes in the required order. We maintain a pointer to the current node in the new tree and adjust the left and right pointers accordingly. At the end of the traversal, the new tree will be the desired tree with the leftmost node as the root and every node having no left child and only one right child.

Algorithmic Steps:

  1. Create a dummy node to be the root of the new tree.
  2. Perform an in-order traversal of the original tree.
  3. During traversal, update the current node's left child to null and set the current node as the right child of the new tree's current node.
  4. Update the current node to its right child.
  5. Continue until all nodes are processed.
  6. Return the right child of the dummy node as the root of the new tree.

Time Complexity: The time complexity of this approach is O(N), where N is the number of nodes in the tree.

Space Complexity: The space complexity is also O(N) due to the space used for the recursion stack and the new tree structure.

class Solution {
    TreeNode prev = new TreeNode(-1);
    TreeNode dummy = prev;

    public TreeNode increasingBST(TreeNode root) {
        if (root == null) return null;
        
        increasingBST(root.left);
        
        prev.right = new TreeNode(root.val);
        prev = prev.right;
        
        increasingBST(root.right);
        
        return dummy.right;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.