Binary Search Tree 1

by Matthew Day

JavaScript

class BinarySearchTree {
    constructor(key=null, value=null, parent=null) {
        this.key = key;
        this.value = value;
        this.parent = parent;
        this.left = null;
        this.right = null;
    }

    insert(key, value) {
        if (this.key == null) {
            this.key = key;
            this.value = value;
        }
        else if (key < this.key) {
            if (this.left == null) {
                this.left = new BinarySearchTree(key, value, this);
            }
            else {
                this.left.insert(key, value);
            }
        }
        else {
            if (this.right == null) {
                this.right = new BinarySearchTree(key, value, this);
            }
            else {
                this.right.insert(key, value);
            }
        }
    }
}

// create a new BST
let tree = new BinarySearchTree();
tree.insert(8);
tree.insert(3);
tree.insert(10);
tree.insert(1);
tree.insert(6);
tree.insert(14);
tree.insert(4);
tree.insert(7);
tree.insert(13);

// find the 3rd largest node in the BST (i.e.)
function findNthLargest(tree=null) {
	if(tree.right) {
  	findNthLargest(tree.right);
  } else if(tree.left) {
  	console.log(tree.parent.key);
  } else {
  	console.log(tree.parent.parent.key);
  }
}

findNthLargest(tree);