Binary Search Tree - Insert
by Hari Menon
JavaScript
'use strict';
const assert = function (expr, msg) {
if (!expr) {
throw new Error(msg);
}
};
class Node {
constructor(data) {
this.key = data;
this.left = null;
this.right = null;
}
}
class BSTNode extends Node {
constructor(data) {
super(data);
this.children = 0;
}
add(data) {
assert(this.key !== data, "data should not exist in the tree already");
this.children++;
if (data < this.key) {
if (this.left == null) {
this.left = new BSTNode(data);
return;
} else {
this.left.add(data);
}
} else if (data > this.key) {
if (this.right == null) {
this.right = new BSTNode(data);
return;
} else {
this.right.add(data);
}
}
}
}
class Tree {
constructor(rootNode) {
assert(rootNode instanceof BSTNode, "rootNode must be of type 'BSTNode'");
this.root = rootNode;
this.nodeCount = 1;
}
insert(data) {
if (data instanceof Array) {
data.forEach(d => this.root.add(d));
this.nodeCount += data.length;
} else {
this.root.add(data);
this.nodeCount++;
}
}
}
const tree = new Tree(new BSTNode(27));
tree.insert(1);
tree.insert(3);
tree.insert(4);
tree.insert([12, 45, 34, 31, 23, 11, 67, 5]);
console.log(tree);