function bstChecker(treeRoot) {
// start at the root, with an arbitrarily low lower bound
// and an arbitrarily high upper bound
var nodeAndBoundsStack = [];
nodeAndBoundsStack.push({
node: treeRoot,
lowerBound: -Infinity,
upperBound: Infinity
});
// depth-first traversal
while (nodeAndBoundsStack.length) {
var nodeAndBounds = nodeAndBoundsStack.pop();
var node = nodeAndBounds.node,
lowerBound = nodeAndBounds.lowerBound,
upperBound = nodeAndBounds.upperBound;
// if this node is invalid, we return false right away
if (node.value < lowerBound || node.value > upperBound) {
return false;
}
if (node.left) {
// this node must be less than the current node
nodeAndBoundsStack.push({
node: node.left,
lowerBound: lowerBound,
upperBound: node.value
});
}
if (node.right) {
// this node must be greater than the current node
nodeAndBoundsStack.push({
node: node.right,
lowerBound: node.value,
upperBound: upperBound
});
}
}
// if none of the nodes were invalid, return true
// (at this point we have checked all nodes)
return true;
}
function bstCheckerRecursive(treeRoot, lowerBound, upperBound) {
lowerBound = (typeof lowerBound !== 'undefined') ? lowerBound : -Infinity;
upperBound = (typeof upperBound !== 'undefined') ? upperBound : Infinity;
if (!treeRoot) return true;
if (treeRoot.value > upperBound || treeRoot.value < lowerBound) {
return false;
}
return bstCheckerRecursive(treeRoot.left, lowerBound, treeRoot.value) &&
bstCheckerRecursive(treeRoot.right, treeRoot.value, upperBound);
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.