class Node{
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree{
constructor() {
this.head = null;
}
add(value){
const node = new Node(value)
if(!this.head) {
this.head = node;
}else{
this.insert(node)
}
}
insert(node){
let cur = this.head;
while(cur) {
if(node.value < cur.value){
if(!cur.left) {
cur.left = node;
break;
}else {
cur = cur.left;
}
}
if(node.value > cur.value){
if(!cur.right) {
cur.right = node;
break;
}else {
cur = cur.right;
}
}
}
}
traverse() {
this._traverse(this.head)
}
_traverse(root) {
if(!root) return null;
this._traverse(root.left)
this._traverse(root.right);
console.log(root.value);
}
}
const tree = new BinarySearchTree();
tree.add(1)
tree.add(2)
tree.add(6)
tree.add(3)
tree.traverse();