Skip to content

Instantly share code, notes, and snippets.

@jack-wong-build
Created February 17, 2014 18:21
Show Gist options
  • Save jack-wong-build/9056105 to your computer and use it in GitHub Desktop.
Save jack-wong-build/9056105 to your computer and use it in GitHub Desktop.
Implement a function to check if a binary tree is a binary search tree.
function checkBST(node){
lastVisited = null;
function checkBSTRecurse (node){
if (node === null) return true;
if ( !checkBSTRecurse(node.left) ) return false;
if (node.val < lastVisited) return false;
lastVisited = node.val;
if ( !checkBSTRecurse(node.right) ) return false;
return true;
}
return checkBSTRecurse(node);
}
// var a = {val: 10, left:null, right: null};
// var b = {val: 9, left:null, right: null};
// var c = {val: 8, left:null, right: null};
// var d = {val: 1, left:null, right: null};
// var e = {val: 11, left:null, right: null};
// var f = {val: 12, left:null, right: null};
// var g = {val: 19, left:null, right: null};
// a.left = b;
// b.left = c;
// c.left = d;
// a.right = e;
// e.right = f;
// f.right = g;
// console.log(checkBST(a));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment