Skip to content

Instantly share code, notes, and snippets.

@woonketwong woonketwong/checkBST
Created Feb 17, 2014

Embed
What would you like to do?
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
You can’t perform that action at this time.