-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtree.js
50 lines (44 loc) · 1010 Bytes
/
tree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Node {
constructor(value){
this.value = value;
this.left = null;
this.right = null;
}
}
class BST {
constructor(){
this.root = null;
}
isEmpty(){
return this.root === null;
}
insert(value){
const newNode = new Node(value);
if(this.isEmpty()){
this.root = newNode;
}else {
this.insertNode(this.root, newNode);
}
}
insertNode(root, newNode){
if(newNode.value < root.value){
if(root.left === null){
root.left = newNode;
}else{
this.insertNode(root.left, newNode);
}
}else{
if(root.right === null){
root,right = newNode;
}else{
this.insertNode(root.right, newNode);
}
}
}
}
const bst = new BST();
console.log(`Tree is empty?`, bst.isEmpty());
bst.insert(12);
bst.insert(5);
bst.insert(15);
bst.insert(21);