Data Structures: Use Breadth First Search in a Binary Search Tree
This commit is contained in:
parent
27feb10c27
commit
f02280cef3
42
Data Structures/bstBFS.js
Normal file
42
Data Structures/bstBFS.js
Normal file
@ -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
|
||||
}
|
Loading…
Reference in New Issue
Block a user