freeCodeCamp/Data Structures/isBST.js

32 lines
891 B
JavaScript

// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/check-if-tree-is-binary-search-tree
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
}
function isBinarySearchTree(tree) {
// Only change code below this line
if (tree.root === null) return true;
const stack = [tree.root];
while (stack.length) {
const node = stack.pop();
const leftChild = node.left;
if (leftChild !== null) {
stack.push(leftChild);
if (node.value <= leftChild.value) return false;
}
const rightChild = node.right;
if (rightChild !== null) {
stack.push(rightChild);
if (node.value > rightChild.value) return false;
}
}
return true;
// Only change code above this line
}