From 487a7107192424301942cc948ca812fe3ceecb7c Mon Sep 17 00:00:00 2001 From: Manish Date: Wed, 30 Aug 2023 13:30:24 +1000 Subject: [PATCH] Data Structures: Check if Tree is Binary Search Tree --- Data Structures/isBST.js | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Data Structures/isBST.js 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 +}