From f02280cef3451d1ae76f35c866e7cb1c22b267da Mon Sep 17 00:00:00 2001 From: Manish Date: Sat, 2 Sep 2023 15:19:59 +1000 Subject: [PATCH] Data Structures: Use Breadth First Search in a Binary Search Tree --- Data Structures/bstBFS.js | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Data Structures/bstBFS.js diff --git a/Data Structures/bstBFS.js b/Data Structures/bstBFS.js new file mode 100644 index 0000000..060f5b4 --- /dev/null +++ b/Data Structures/bstBFS.js @@ -0,0 +1,42 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/use-breadth-first-search-in-a-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; + // Only change code below this line + this.bfs = (order) => { + if (this.root === null) return null; + const values = []; + let q = [this.root]; + let nextQ = []; + while (q.length) { + for (let node of q) { + values.push(node.value); + order(node, nextQ); + } + q = nextQ; + nextQ = []; + } + return values; + }; + + this.levelOrder = () => { + return this.bfs((node, nextQ) => { + if (node.left !== null) nextQ.push(node.left); + if (node.right !== null) nextQ.push(node.right); + }); + }; + + this.reverseLevelOrder = () => { + return this.bfs((node, nextQ) => { + if (node.right !== null) nextQ.push(node.right); + if (node.left !== null) nextQ.push(node.left); + }); + }; + // Only change code above this line +}