DEV Community

Subramanya Chakravarthy
Subramanya Chakravarthy

Posted on

2 1

Construct Binary Search Tree from Preorder Traversal - LeetCode

Return the root node of a binary search tree that matches the given preorder traversal.

So basically return a Binary Search Tree from an array of elements that are in preorder

For a binary search tree at any given nodeany descendant of node.left < node.val and any descendant of node.right > node.val

Algorithm:

  1. Loop through each element
  2. find the leaf node to insert
  3. repeat

Code:

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} preorder
 * @return {TreeNode}
 */
var bstFromPreorder = function(preorder) {
    let root = new TreeNode(preorder[0])
    for(let i = 1; i < preorder.length; i++) {
        root = insert(root, preorder[i])
    }
    return root
};

var insert = function(node, elem) {
    if(!node) return new TreeNode(elem)
    if(node.val > elem) {
        node.left = insert(node.left, elem)
    } else {
        node.right = insert(node.right, elem)
    }
    return node
}

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

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