-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathRedBlack Tree.html
More file actions
148 lines (119 loc) · 3.27 KB
/
RedBlack Tree.html
File metadata and controls
148 lines (119 loc) · 3.27 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
const RED = true;
const BLACK = false;
class Node {
constructor(key, value) {
this.key = key;
this.value = value;
this.left = null;
this.right = null;
this.color = RED;
}
}
class RedBlackTree {
constructor() {
this.root = null;
this.size = 0;
}
add(key, value) {
this.root = this._add(this.root, key, value);
this.root.color = BLACK
}
_add(node, key, value) {
if (!node) {
this.size++;
return new Node(key, value);
}
if (key < node.key) {
node.left = this._add(node.left, key, value)
} else if (key > node.key) {
node.right = this._add(node.right, key, value)
} else {
node.value = value
}
if (this.isRed(node.right) && !this.isRed(node.left)) {
node = this.leftRotate(node)
}
if (this.isRed(node.left) && this.isRed(node.left.left)) {
node = this.rightRotate(node)
}
if (this.isRed(node.left) && this.isRed(node.right)) {
this.flipColors(node)
}
return node
}
// node x
// / \ 左旋转 / \
// T1 x ---------> node T3
// / \ / \
// T2 T3 T1 T2
leftRotate(node) {
let x = node.right;
node.right = x.left;
x.left = node;
x.color = node.color;
node.color = RED;
return x
}
// node x
// / \ 右旋转 / \
// x T2 -------> y node
// / \ / \
// y T1 T1 T2
rightRotate(node) {
let x = node.left;
node.left = x.right;
x.right = node;
x.color = node.color;
node.color = RED;
return x
}
flipColors(node) {
node.color = RED;
node.left.color = BLACK;
node.right.color = BLACK
}
getSize() {
return this.size
}
isEmpty() {
return this.size === 0
}
isRed(node) {
if (!node) return BLACK;
return node.color
}
}
function main() {
let n = 10000000,
nums = [];
for (let i = 0; i < n; i++) {
nums.push(i)
}
let start = new Date().getTime(),
RBTree = new RedBlackTree();
for(num of nums){
RBTree.add(num, null)
}
let end = new Date().getTime(),
time = (end - start) / 1000;
console.log(time)
}
main()
// let RBTree = new RedBlackTree();
// RBTree.add(26, 26)
// RBTree.add(17, 17)
// RBTree.add(41, 41)
// RBTree.add(30, 30)
// RBTree.add(47, 47)
// console.log(RBTree)
</script>
</body>
</html>