DEV Community

codingpineapple
codingpineapple

Posted on

1 1

LeetCode 897. Increasing Order Search Tree (javascript solution)

Description:

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.

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

var increasingBST = function(root) {
    // Create dummy head
    let ans = new TreeNode(0);
    // Pointer to the current node
    let cur = ans;
    // Add node to the right pointer of cur and remove the left pointer of cur then change cur to point to node
    function inorder(node) {
        if (node === null) return;
        inorder(node.left);
        node.left = null;
        cur.right = node;
        cur = node;
        inorder(node.right);
    }
    inorder(root);
    return ans.right;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️