Skip to content

Instantly share code, notes, and snippets.

View RylanBauermeister's full-sized avatar

RylanBauermeister

View GitHub Profile
to_array(){
if(!this.root) return []
let queue = [this.root]
let result = []
while(queue.length !== 0) {
let current = queue.shift()
result.push(current.val)
if(current.left) queue.push(current.left)
if(current.right) queue.push(current.right)
}
//Deletes the lowest value from the tree by tracing leftmost from the root
removeLowest(){
if(!this.root) return false;
this.delete(this.leftmost(this.root))
}
//Deletes the highest value from the tree by tracing rightmost from the root
removeHighest(){
if(!this.root) return false;
this.delete(this.rightmost(this.root))
else if(node.right && node.left) {
let right = this.leftmost(node.right);
node.val = right.val;
this.delete(right)
return true;
}
//If it has only a right child, we replace the node we are deleting with its child.
else if (node.right && !node.left){
let right = node.right;
node.val = right.val;
node.left = right.left;
node.right = right.right;
if(node.right) node.right.parent = node;
if(node.left) node.left.parent = node;
right = null;
return true;
//If it has no children, it can be safely plucked.
if(!node.right && !node.left){
if(!node.parent){
this.root = null
} else if(node.parent.left === node){
node.parent.left = null;
} else {
node.parent.right = null;
}
return true;
delete(node){
if(!node.right && !node.left){
}
else if (node.right && !node.left){
}
else if (!node.right && node.left){
}
else if(node.right && node.left) {
}
}
//Removing from a binary tree
remove(val){
let node = this.getNode(val)
if(!node){
return false;
} else {
return this.delete(node)
}
}
//Inserting into a binary tree
insert(val) {
//If the root is null, initialize the tree with the value as its root.
if(!this.root) {
this.root = new Node(val)
return;
}
//Otherwise, search for the correct location.
let current = this.root
import Node from './node'
export default class BST {
constructor(){
this.root = null;
}
//functions go here
export default class Node {
constructor(val){
this.val = val;
this.parent = null;
this.left = null;
this.right = null;
}
}