Created
March 18, 2020 14:50
-
-
Save Prottoy2938/d2a8796c476c64d09c772ce0a9d304a1 to your computer and use it in GitHub Desktop.
Binary Search Tree Validation in JavaScript
This file contains 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
//Solution 1 | |
const isValidBST = function(root, min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER) { | |
if(root == null) return true | |
if(root.val >= max || root.val <= min) return false | |
return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max) | |
}; | |
//Solution 2 | |
const isValidBST = root => { | |
if (!root) return true; | |
const stack = []; | |
let prevNode = null; | |
while(root != null || stack.length > 0) { | |
while(root != null) { | |
stack.push(root); | |
root = root.left; | |
} | |
root = stack.pop(); | |
if (prevNode && prevNode.val >= root.val) return false; | |
prevNode = root; | |
root = root.right; | |
} | |
return true; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment