Increasing Order Search Tree

easy binary tree bst in-order traversal

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.

Inputroot = [5, 3, 6, 2, 4, null, 8, 1]
Output[1, null, 2, null, 3, null, 4, null, 5, null, 6, null, 8]
The in-order sequence is 1, 2, 3, 4, 5, 6, 8. Each value becomes a right child of the previous one, forming a right-leaning chain.

def increasingBST(root):
    dummy = TreeNode()
    cur = dummy
    def inorder(node):
        nonlocal cur
        if not node:
            return
        inorder(node.left)
        node.left = None
        cur.right = node
        cur = node
        inorder(node.right)
    inorder(root)
    return dummy.right
function increasingBST(root) {
  const dummy = new TreeNode();
  let cur = dummy;
  function inorder(node) {
    if (!node) return;
    inorder(node.left);
    node.left = null;
    cur.right = node;
    cur = node;
    inorder(node.right);
  }
  inorder(root);
  return dummy.right;
}
class Solution {
    private TreeNode cur;
    public TreeNode increasingBST(TreeNode root) {
        TreeNode dummy = new TreeNode();
        cur = dummy;
        inorder(root);
        return dummy.right;
    }
    private void inorder(TreeNode node) {
        if (node == null) return;
        inorder(node.left);
        node.left = null;
        cur.right = node;
        cur = node;
        inorder(node.right);
    }
}
class Solution {
    TreeNode* cur;
    void inorder(TreeNode* node) {
        if (!node) return;
        inorder(node->left);
        node->left = nullptr;
        cur->right = node;
        cur = node;
        inorder(node->right);
    }
public:
    TreeNode* increasingBST(TreeNode* root) {
        TreeNode dummy;
        cur = &dummy;
        inorder(root);
        return dummy.right;
    }
};
Time: O(n) Space: O(h)