diff --git a/Data Structures/isBST.js b/Data Structures/isBST.js new file mode 100644 index 0000000..edb9742 --- /dev/null +++ b/Data Structures/isBST.js @@ -0,0 +1,31 @@ +// 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 +}