-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinarySearchTree.js
85 lines (76 loc) · 1.99 KB
/
binarySearchTree.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class Node {
constructor(data){
this.data = data;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor(){
this.root = null;
}
insert(data) {
let node = new Node(data);
if (this.root == null) {
this.root = node;
} else {
this.insertNode(this.root, node);
}
}
insertNode(root, newNode){
if (newNode.data < root.data) {
if(root.left == null) {
root.left = newNode;
} else {
this.insertNode(root.left, newNode);
}
} else if(newNode.data > root.data) {
if (root.right == null) {
root.right = newNode;
} else {
this.insertNode(root.right, newNode);
}
}
}
getRootNode() {
return this.root;
}
// traversal
preorder(root) {
if (root != null){
console.log(root.data); // first line - P L R
this.preorder(root.left); // second line
this.preorder(root.right); // third line
}
}
inorder(root) {
if (root != null) {
this.inorder(root.left); // first line // L P R
console.log(root.data); // second line
this.inorder(root.right); // third line
}
}
postorder(root){
if (root != null) {
this.postorder(root.left); // first line // L R P
this.postorder(root.right); // second line
console.log(root.data); // third line
}
}
}
let bst = new BinarySearchTree();
bst.insert(5);
bst.insert(3);
bst.insert(1);
bst.insert(6);
bst.insert(4);
let root = bst.getRootNode();
console.log("Preorder");
bst.preorder(root);
console.log("\n")
console.log("Inorder");
bst.inorder(root);
console.log("\n")
console.log("Posteorder");
bst.postorder(root);
console.log("\n")