* Perform the splay operation for the given key. Moves the node with * the given key to the top of the tree. If no node has the given * key, the last node on the search path is moved to the top of the * tree. This is the simplified top-down splaying algorithm from: * "Self-adjusting Bin
(key)
| 201 | * @private |
| 202 | */ |
| 203 | splay_(key) { |
| 204 | if (this.isEmpty()) return; |
| 205 | // Create a dummy node. The use of the dummy node is a bit |
| 206 | // counter-intuitive: The right child of the dummy node will hold |
| 207 | // the L tree of the algorithm. The left child of the dummy node |
| 208 | // will hold the R tree of the algorithm. Using a dummy node, left |
| 209 | // and right will always be nodes and we avoid special cases. |
| 210 | let dummy, left, right; |
| 211 | dummy = left = right = new SplayTreeNode(null, null); |
| 212 | let current = this.root_; |
| 213 | while (true) { |
| 214 | if (key < current.key) { |
| 215 | if (current.left === null) break; |
| 216 | if (key < current.left.key) { |
| 217 | // Rotate right. |
| 218 | const tmp = current.left; |
| 219 | current.left = tmp.right; |
| 220 | tmp.right = current; |
| 221 | current = tmp; |
| 222 | if (current.left === null) break; |
| 223 | } |
| 224 | // Link right. |
| 225 | right.left = current; |
| 226 | right = current; |
| 227 | current = current.left; |
| 228 | } else if (key > current.key) { |
| 229 | if (current.right === null) break; |
| 230 | if (key > current.right.key) { |
| 231 | // Rotate left. |
| 232 | const tmp = current.right; |
| 233 | current.right = tmp.left; |
| 234 | tmp.left = current; |
| 235 | current = tmp; |
| 236 | if (current.right === null) break; |
| 237 | } |
| 238 | // Link left. |
| 239 | left.right = current; |
| 240 | left = current; |
| 241 | current = current.right; |
| 242 | } else { |
| 243 | break; |
| 244 | } |
| 245 | } |
| 246 | // Assemble. |
| 247 | left.right = current.left; |
| 248 | right.left = current.right; |
| 249 | current.left = dummy.right; |
| 250 | current.right = dummy.left; |
| 251 | this.root_ = current; |
| 252 | } |
| 253 | |
| 254 | /** |
| 255 | * Performs a preorder traversal of the tree. |
no test coverage detected