Implement BST and Traversal
//implementing BST
//condition - parent node has two child nodes
//left - smaller value
//right - larger value
// No duplicates assume
//max -depth of BST
//find if a value is present or not
//insert
//update
//delete
//Tree Travesal for everything - it is just visiting all nodes
//Bread first search - BFS
//Depth first search - DFS
//pre-order
//post-order
//in-order
class Node {
constructor(val) {
this.val = val;
this.child = [];
}
}
class BST {
constructor() {
this.root = null;
}
insert(val) {
const newNode = new Node(parent, val);
if(this.root === null) {
this.root = newNode;
return this;
}
this.insertHelper(this.root, newNode);
return this;
}
bfs() {
let tempQ = [];
if(this.root === null) return;
tempQ.push(this.root);
while(tempQ.length !== 0) {
let current = tempQ[0];
if(current.left !== null) tempQ.push(current.left);
if(current.right !== null) tempQ.push(current.right);
console.log(current.val);
tempQ.shift();
console.log(tempQ);
}
}
preOrder() {
if(this.root === null) return;
let current = this.root;
this.preOrderHelper(current);
}
preOrderHelper(current) {
console.log(current.val);
if(current.left) this.preOrderHelper(current.left);
if(current.right) this.preOrderHelper(current.right);
}
postOrder() {
if(this.root === null) return;
let current = this.root;
this.postOrderHelper(current);
}
postOrderHelper(current) {
if(current.left) this.postOrderHelper(current.left);
console.log(current.val);
if(current.right) this.postOrderHelper(current.right);
}
inOrder() {
if(this.root === null) return;
let current = this.root;
this.inOrderHelper(current);
}
inOrderHelper(current) {
if(current.left) this.inOrderHelper(current.left);
if(current.right) this.inOrderHelper(current.right);
console.log(current.val);
}
insertHelper(current, newNode) {
if(newNode.val < current.val) {
if(current.left === null) {
current.left = newNode;
return;
}
else {
current = current.left;
this.insertHelper(current, newNode);
}
}
else if(newNode.val > current.val) {
if(current.right === null) {
current.right = newNode;
return;
}
else {
current = current.right;
this.insertHelper(current, newNode);
}
}
else {
return;
}
} //END
}
const myBST = new BST();
myBST.insert(50);
myBST.insert(40);
myBST.insert(60);
myBST.insert(45);
myBST.insert(30);
myBST.insert(10);
myBST.insert(75);
console.log(myBST);