Hackerrank-JavaScript-Solutions
Hackerrank-JavaScript-Solutions copied to clipboard
bst in js
let node = (data) => ({
left: null,
right: null,
data: data
})
let bst = {
root: null,
insert: (root = bst.root, data) => {
if (root === null) {
bst.root = node(data);
} else {
if (data < root.data) {
root.left = root.left === null ? node(data) : bst.insert(root.left, data);
}
else {
root.right = root.right === null ? node(data) : bst.insert(root.right, data);
}
}
return root;
},
postorder: (root) => {
if (root !== null) {
bst.postorder(root.left);
bst.postorder(root.right);
console.log(root.data);
}
},
inorder: (root) => {
if (root !== null) {
bst.inorder(root.left);
console.log(root.data);
bst.inorder(root.right);
}
},
remove: (root, data) => {
if (root === null) return null;
else if (data > root.data) {
root.right = bst.remove(root.right, data);
return root;
}
else if (data < root.data) {
root.left = bst.remove(root.left, data);
return root;
}
else {
if (root.left == null && root.right === null) {
root = null;
return root;
}
if (root.left === null) {
root = root.right;
return root;
}
else if (root.right === null) {
root = root.left;
return root;
}
// Deleting node with two children
// minumum node of the rigt subtree
// is stored in aux
let aux = bst.findMinNode(root.right);
root.data = aux.data;
root.right = bst.remove(root.right, aux.data);
return root;
}
},
findMinNode: (root) =>{
if(root.left === null) return root;
root = bst.findMinNode(root.left);
return root;
}
}
bst.insert(bst.root, 15);
bst.insert(bst.root, 25);
bst.insert(bst.root, 10);
bst.insert(bst.root, 7);
bst.insert(bst.root, 22);
bst.insert(bst.root, 17);
bst.insert(bst.root, 13);
bst.insert(bst.root, 5);
bst.insert(bst.root, 9);
bst.insert(bst.root, 27);
console.log(JSON.stringify(bst.root));
bst.remove(bst.root, 5);
bst.remove(bst.root, 7);
// bst.inorder(bst.root);
bst.remove(bst.root, 15);
bst.inorder(bst.root);
https://repl.it/repls/FairFaroffMedian