-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathBST_implementation.js
59 lines (51 loc) · 1.09 KB
/
BST_implementation.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
59
// BST implementation in Javascript
class Node{
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
};
};
class BinarySearchTree{
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);
};
};
};
};
function print_f(root) {
if (root === null) {
return false;
}
console.log(root.data);
print_f(root.left);
print_f(root.right);
}
const BST = new BinarySearchTree();
BST.insert(1);
BST.insert(2);
BST.insert(3);
print_f(BST.root);
//Output :
// 1 2 3