freeCodeCamp/Data Structures/bstBFS.js

43 lines
1.1 KiB
JavaScript

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