-
Notifications
You must be signed in to change notification settings - Fork 3
/
Bst.js
executable file
·58 lines (54 loc) · 1.27 KB
/
Bst.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
51
52
53
54
55
56
57
58
class Node{
constructor(data, left = null, right = null){
this.data = data;
this.left = left;
this.right = right;
}
}
class BST{
constructor(){
this.root = null;
}
insert(data){
var newNode = new Node(data);
if(this.root == null){
this.root = newNode;
}else{
this.insertNode(this.root, newNode);
}
}
insertNode(node, newNode){
if(newNode.data < node.data){
if(node.left == null){
node.left = newNode;
}else{
this.insertNode(node.left, newNode);
}
}else{
if(node.right == null){
node.right = newNode;
}else{
this.insertNode(node.right, newNode);
}
}
}
inorder(node){
if(node!=null){
this.inorder(node.left);
console.log(node.data);
this.inorder(node.right);
}
}
getRootNode(){
return this.root;
}
}
const BSTInstance = new BST();
BSTInstance.insert(4);
BSTInstance.insert(2);
BSTInstance.insert(1);
BSTInstance.insert(6);
BSTInstance.insert(7);
BSTInstance.insert(5);
BSTInstance.insert(3);
BSTInstance.inorder(BSTInstance.getRootNode());