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:
- Loop through each element
- find the leaf node to insert
- 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
}
Top comments (0)