JSFiddle - React, Tailwind, and code Playground

by Anurag Udasi

JavaScript

const Node = name => {
	return {
  	name,
    left: null,
    right: null,
  };
};

class BSTree {
	constructor() {
  	this.root = null;
    
    this.pint = (node) => {
    	if(!node) return;
      this.pint(node.left);
      console.log(node.name);
      this.pint(node.right);
    };
  }
  
  insert(name) {
  	const node = Node(name);
  	if(!this.root) { this.root = node; }
    else {
    	let current = this.root;
      let prev = null;
      while(current) {
      	prev = current;
      	if(node.name < current.name) { current = current.left; }
        else { current = current.right; }
      }
      if (node.name < prev.name) {
      	node.left = prev.left;
        prev.left = node;
      } else {
        node.right = prev.right;
        prev.right = node;
      }
    }
  }
  
 	delete(name) {
    if(!this.root) return;
    if(this.root.name === name) {
      if (this.root.left) {
      	this.root.left.right = this.root.right;
      	this.root = this.root.left;   
      }
      else if (this.root.right) {
      	this.root.right.left = this.root.left;
      	this.root = this.root.right;
      }
      else this.root = null;
    }
    let prev = null;
    let current = this.root;
    while(current) {
      prev = current;
      if (current.left && current.left.name === name) {
        prev.left = current.left.left;
        break;
      } else if (current.right && current.right.name === name) {
        prev.right = current.right.right;
        break;
      }
      else {
        if (name < current.name) current = current.left;
        else current = current.right;
      }
    }
  }
};

const tree = new BSTree();
tree.insert(2);
tree.insert(1);
tree.insert(3);
tree.insert(9);
tree.insert(8);
tree.insert(6);
tree.insert(5);
tree.insert(0);
tree.insert(-1);
tree.delete(2);
tree.pint(tree.root);