freeCodeCamp/Data Structures/bstDFS.js

55 lines
1.4 KiB
JavaScript
Raw Normal View History

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