Data Structures: Use Breadth First Search in a Binary Search Tree
This commit is contained in:
parent
0e82393bfc
commit
833ef203d9
54
Data Structures/bstDFS.js
Normal file
54
Data Structures/bstDFS.js
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/use-depth-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.inorder = () => {
|
||||||
|
if (this.root === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const values = [];
|
||||||
|
const traverse = (node) => {
|
||||||
|
if (node.left !== null) traverse(node.left);
|
||||||
|
values.push(node.value);
|
||||||
|
if (node.right !== null) traverse(node.right);
|
||||||
|
};
|
||||||
|
traverse(this.root);
|
||||||
|
return values;
|
||||||
|
};
|
||||||
|
|
||||||
|
this.preorder = () => {
|
||||||
|
if (this.root === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const values = [];
|
||||||
|
const traverse = (node) => {
|
||||||
|
values.push(node.value);
|
||||||
|
if (node.left !== null) traverse(node.left);
|
||||||
|
if (node.right !== null) traverse(node.right);
|
||||||
|
};
|
||||||
|
traverse(this.root);
|
||||||
|
return values;
|
||||||
|
};
|
||||||
|
|
||||||
|
this.postorder = () => {
|
||||||
|
if (this.root === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const values = [];
|
||||||
|
const traverse = (node) => {
|
||||||
|
if (node.left !== null) traverse(node.left);
|
||||||
|
if (node.right !== null) traverse(node.right);
|
||||||
|
values.push(node.value);
|
||||||
|
};
|
||||||
|
traverse(this.root);
|
||||||
|
return values;
|
||||||
|
};
|
||||||
|
// Only change code above this line
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user