Created
April 21, 2020 04:05
-
-
Save efuquen/3b1fc811a999b14aba40ed9623d11326 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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