Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save efuquen/3b1fc811a999b14aba40ed9623d11326 to your computer and use it in GitHub Desktop.
Save efuquen/3b1fc811a999b14aba40ed9623d11326 to your computer and use it in GitHub Desktop.
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number[]} preorder
* @return {TreeNode}
*/
function TreeNode(val) {
var node = {};
node.val = val;
node.left = node.right = null;
return node;
}
var bstFromPreorder = function(preorder) {
var root = TreeNode(preorder[0]);
var stack = [root];
for (var i = 1; i < preorder.length; i++) {
var temp = null;
// Keep on popping while the next value is greater than
// stack's top value.
while ( stack.length > 0 && preorder[i] > stack[stack.length - 1].val )
temp = stack.pop();
// Make this greater value as the right child
// and push it to the stack
if ( temp != null)
{
temp.right = TreeNode(preorder[i]);
stack.push(temp.right);
// If the next value is less than the stack's top
// value, make this value as the left child of the
// stack's top node. Push the new node to stack
} else {
stack[stack.length - 1].left = TreeNode(preorder[i]);
stack.push(stack[stack.length - 1].left);
}
}
return root;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment