loading...

Construct Binary Search Tree from Preorder Traversal - LeetCode

chakrihacker profile image Subramanya Chakravarthy ・1 min read

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
}

Discussion

markdown guide