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