Data Structures: Check if Tree is Binary Search Tree

This commit is contained in:
Manish 2023-08-30 13:30:24 +10:00
parent 7e2b75ac96
commit 487a710719

31
Data Structures/isBST.js Normal file
View File

@ -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
}