-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTree.js
More file actions
100 lines (89 loc) · 2.56 KB
/
Copy pathBinarySearchTree.js
File metadata and controls
100 lines (89 loc) · 2.56 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(data) {
const 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);
}
}
remove(data) {
this.root = this.removeNode(this.root, data);
}
removeNode(node, key) {
if (node === null) return null;
else if (key < node.data) {
node.left = this.removeNode(node.left, key);
return node;
} else if (key > node.data) {
node.right = this.removeNode(node.right, key);
return node;
} else {
if (node.left === null && node.right === null) {
node = null;
return node;
}
if (node.left === null) {
node = node.right;
return node;
} else if (node.right === null) {
node = node.left;
return node;
}
const aux = this.findMinNode(node.right);
node.data = aux.data;
node.right = this.removeNode(node.right, aux.data);
return node;
}
}
inOrder(node) {
if (node !== null) {
this.inOrder(node.left);
console.log(node.data);
this.inOrder(node.right);
}
}
preOrder(node) {
if (node !== null) {
console.log(node.data);
this.preOrder(node.left);
this.preOrder(node.right);
}
}
postOrder(node) {
if (node !== null) {
this.postOrder(node.left);
this.postOrder(node.right);
console.log(node.data);
}
}
findMinNode(node) {
if (node.left === null) return node;
else return this.findMinNode(node.left);
}
getRootNode() {
return this.root;
}
search(node, data) {
if (node === null) return null;
else if (data < node.data) return this.search(node.left, data);
else if (data > node.data) return this.search(node.right, data);
else return node;
}
}