Skip to content

Instantly share code, notes, and snippets.

@Prottoy2938
Created March 18, 2020 14:50
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 Prottoy2938/d2a8796c476c64d09c772ce0a9d304a1 to your computer and use it in GitHub Desktop.
Save Prottoy2938/d2a8796c476c64d09c772ce0a9d304a1 to your computer and use it in GitHub Desktop.
Binary Search Tree Validation in JavaScript
//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