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)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay