gitee.com/quant1x/gox@v1.21.2/util/redblacktree/redblacktree.go (about) 1 // Copyright (c) 2015, Emir Pasic. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package redblacktree implements a red-black tree. 6 // 7 // Used by TreeSet and TreeMap. 8 // 9 // Structure is not thread safe. 10 // 11 // References: http://en.wikipedia.org/wiki/Red%E2%80%93black_tree 12 package redblacktree 13 14 import ( 15 "fmt" 16 "gitee.com/quant1x/gox/util/internal" 17 "sync" 18 ) 19 20 func assertTreeImplementation() { 21 var _ internal.Tree = (*Tree)(nil) 22 } 23 24 type color bool 25 26 const ( 27 black, red color = true, false 28 ) 29 30 // Tree holds elements of the red-black tree 31 type Tree struct { 32 Root *Node 33 size int 34 Comparator internal.Comparator 35 mutex sync.RWMutex 36 } 37 38 // Node is a single element within the tree 39 type Node struct { 40 Key interface{} 41 Value interface{} 42 color color 43 Left *Node 44 Right *Node 45 Parent *Node 46 } 47 48 // NewWith instantiates a red-black tree with the custom comparator. 49 func NewWith(comparator internal.Comparator) *Tree { 50 return &Tree{Comparator: comparator} 51 } 52 53 // NewWithIntComparator instantiates a red-black tree with the IntComparator, i.e. keys are of type int. 54 func NewWithIntComparator() *Tree { 55 return &Tree{Comparator: internal.IntComparator} 56 } 57 58 // NewWithStringComparator instantiates a red-black tree with the StringComparator, i.e. keys are of type string. 59 func NewWithStringComparator() *Tree { 60 return &Tree{Comparator: internal.StringComparator} 61 } 62 63 // Put inserts node into the tree. 64 // Key should adhere to the comparator's type assertion, otherwise method panics. 65 func (tree *Tree) Put(key interface{}, value interface{}) { 66 tree.mutex.Lock() 67 defer tree.mutex.Unlock() 68 var insertedNode *Node 69 if tree.Root == nil { 70 // Assert key is of comparator's type for initial tree 71 tree.Comparator(key, key) 72 tree.Root = &Node{Key: key, Value: value, color: red} 73 insertedNode = tree.Root 74 } else { 75 node := tree.Root 76 loop := true 77 for loop { 78 compare := tree.Comparator(key, node.Key) 79 switch { 80 case compare == 0: 81 node.Key = key 82 node.Value = value 83 return 84 case compare < 0: 85 if node.Left == nil { 86 node.Left = &Node{Key: key, Value: value, color: red} 87 insertedNode = node.Left 88 loop = false 89 } else { 90 node = node.Left 91 } 92 case compare > 0: 93 if node.Right == nil { 94 node.Right = &Node{Key: key, Value: value, color: red} 95 insertedNode = node.Right 96 loop = false 97 } else { 98 node = node.Right 99 } 100 } 101 } 102 insertedNode.Parent = node 103 } 104 tree.insertCase1(insertedNode) 105 tree.size++ 106 } 107 108 // Get searches the node in the tree by key and returns its value or nil if key is not found in tree. 109 // Second return parameter is true if key was found, otherwise false. 110 // Key should adhere to the comparator's type assertion, otherwise method panics. 111 func (tree *Tree) Get(key interface{}) (value interface{}, found bool) { 112 tree.mutex.RLock() 113 defer tree.mutex.RUnlock() 114 node := tree.lookup(key) 115 if node != nil { 116 return node.Value, true 117 } 118 return nil, false 119 } 120 121 // Remove remove the node from the tree by key. 122 // Key should adhere to the comparator's type assertion, otherwise method panics. 123 func (tree *Tree) Remove(key interface{}) { 124 tree.mutex.Lock() 125 defer tree.mutex.Unlock() 126 var child *Node 127 node := tree.lookup(key) 128 if node == nil { 129 return 130 } 131 if node.Left != nil && node.Right != nil { 132 pred := node.Left.maximumNode() 133 node.Key = pred.Key 134 node.Value = pred.Value 135 node = pred 136 } 137 if node.Left == nil || node.Right == nil { 138 if node.Right == nil { 139 child = node.Left 140 } else { 141 child = node.Right 142 } 143 if node.color == black { 144 node.color = nodeColor(child) 145 tree.deleteCase1(node) 146 } 147 tree.replaceNode(node, child) 148 if node.Parent == nil && child != nil { 149 child.color = black 150 } 151 } 152 tree.size-- 153 } 154 155 // Empty returns true if tree does not contain any nodes 156 func (tree *Tree) Empty() bool { 157 return tree.size == 0 158 } 159 160 // Size returns number of nodes in the tree. 161 func (tree *Tree) Size() int { 162 return tree.size 163 } 164 165 // Keys returns all keys in-order 166 func (tree *Tree) Keys() []interface{} { 167 keys := make([]interface{}, tree.size) 168 it := tree.Iterator() 169 for i := 0; it.Next(); i++ { 170 keys[i] = it.Key() 171 } 172 return keys 173 } 174 175 // Values returns all values in-order based on the key. 176 func (tree *Tree) Values() []interface{} { 177 values := make([]interface{}, tree.size) 178 it := tree.Iterator() 179 for i := 0; it.Next(); i++ { 180 values[i] = it.Value() 181 } 182 return values 183 } 184 185 // Left returns the left-most (min) node or nil if tree is empty. 186 func (tree *Tree) Left() *Node { 187 var parent *Node 188 current := tree.Root 189 for current != nil { 190 parent = current 191 current = current.Left 192 } 193 return parent 194 } 195 196 // Right returns the right-most (max) node or nil if tree is empty. 197 func (tree *Tree) Right() *Node { 198 var parent *Node 199 current := tree.Root 200 for current != nil { 201 parent = current 202 current = current.Right 203 } 204 return parent 205 } 206 207 // Floor Finds floor node of the input key, return the floor node or nil if no floor is found. 208 // Second return parameter is true if floor was found, otherwise false. 209 // 210 // Floor node is defined as the largest node that is smaller than or equal to the given node. 211 // A floor node may not be found, either because the tree is empty, or because 212 // all nodes in the tree are larger than the given node. 213 // 214 // Key should adhere to the comparator's type assertion, otherwise method panics. 215 func (tree *Tree) Floor(key interface{}) (floor *Node, found bool) { 216 found = false 217 node := tree.Root 218 for node != nil { 219 compare := tree.Comparator(key, node.Key) 220 switch { 221 case compare == 0: 222 return node, true 223 case compare < 0: 224 node = node.Left 225 case compare > 0: 226 floor, found = node, true 227 node = node.Right 228 } 229 } 230 if found { 231 return floor, true 232 } 233 return nil, false 234 } 235 236 // Ceiling finds ceiling node of the input key, return the ceiling node or nil if no ceiling is found. 237 // Second return parameter is true if ceiling was found, otherwise false. 238 // 239 // Ceiling node is defined as the smallest node that is larger than or equal to the given node. 240 // A ceiling node may not be found, either because the tree is empty, or because 241 // all nodes in the tree are smaller than the given node. 242 // 243 // Key should adhere to the comparator's type assertion, otherwise method panics. 244 func (tree *Tree) Ceiling(key interface{}) (ceiling *Node, found bool) { 245 found = false 246 node := tree.Root 247 for node != nil { 248 compare := tree.Comparator(key, node.Key) 249 switch { 250 case compare == 0: 251 return node, true 252 case compare < 0: 253 ceiling, found = node, true 254 node = node.Left 255 case compare > 0: 256 node = node.Right 257 } 258 } 259 if found { 260 return ceiling, true 261 } 262 return nil, false 263 } 264 265 // Clear removes all nodes from the tree. 266 func (tree *Tree) Clear() { 267 tree.mutex.Lock() 268 defer tree.mutex.Unlock() 269 tree.Root = nil 270 tree.size = 0 271 } 272 273 // String returns a string representation of container 274 func (tree *Tree) String() string { 275 str := "RedBlackTree\n" 276 if !tree.Empty() { 277 output(tree.Root, "", true, &str) 278 } 279 return str 280 } 281 282 func (node *Node) String() string { 283 return fmt.Sprintf("%v", node.Key) 284 } 285 286 func output(node *Node, prefix string, isTail bool, str *string) { 287 if node.Right != nil { 288 newPrefix := prefix 289 if isTail { 290 newPrefix += "│ " 291 } else { 292 newPrefix += " " 293 } 294 output(node.Right, newPrefix, false, str) 295 } 296 *str += prefix 297 if isTail { 298 *str += "└── " 299 } else { 300 *str += "┌── " 301 } 302 *str += node.String() + "\n" 303 if node.Left != nil { 304 newPrefix := prefix 305 if isTail { 306 newPrefix += " " 307 } else { 308 newPrefix += "│ " 309 } 310 output(node.Left, newPrefix, true, str) 311 } 312 } 313 314 func (tree *Tree) lookup(key interface{}) *Node { 315 node := tree.Root 316 for node != nil { 317 compare := tree.Comparator(key, node.Key) 318 switch { 319 case compare == 0: 320 return node 321 case compare < 0: 322 node = node.Left 323 case compare > 0: 324 node = node.Right 325 } 326 } 327 return nil 328 } 329 330 func (node *Node) grandparent() *Node { 331 if node != nil && node.Parent != nil { 332 return node.Parent.Parent 333 } 334 return nil 335 } 336 337 func (node *Node) uncle() *Node { 338 if node == nil || node.Parent == nil || node.Parent.Parent == nil { 339 return nil 340 } 341 return node.Parent.sibling() 342 } 343 344 func (node *Node) sibling() *Node { 345 if node == nil || node.Parent == nil { 346 return nil 347 } 348 if node == node.Parent.Left { 349 return node.Parent.Right 350 } 351 return node.Parent.Left 352 } 353 354 func (tree *Tree) rotateLeft(node *Node) { 355 right := node.Right 356 tree.replaceNode(node, right) 357 node.Right = right.Left 358 if right.Left != nil { 359 right.Left.Parent = node 360 } 361 right.Left = node 362 node.Parent = right 363 } 364 365 func (tree *Tree) rotateRight(node *Node) { 366 left := node.Left 367 tree.replaceNode(node, left) 368 node.Left = left.Right 369 if left.Right != nil { 370 left.Right.Parent = node 371 } 372 left.Right = node 373 node.Parent = left 374 } 375 376 func (tree *Tree) replaceNode(old *Node, new *Node) { 377 if old.Parent == nil { 378 tree.Root = new 379 } else { 380 if old == old.Parent.Left { 381 old.Parent.Left = new 382 } else { 383 old.Parent.Right = new 384 } 385 } 386 if new != nil { 387 new.Parent = old.Parent 388 } 389 } 390 391 func (tree *Tree) insertCase1(node *Node) { 392 if node.Parent == nil { 393 node.color = black 394 } else { 395 tree.insertCase2(node) 396 } 397 } 398 399 func (tree *Tree) insertCase2(node *Node) { 400 if nodeColor(node.Parent) == black { 401 return 402 } 403 tree.insertCase3(node) 404 } 405 406 func (tree *Tree) insertCase3(node *Node) { 407 uncle := node.uncle() 408 if nodeColor(uncle) == red { 409 node.Parent.color = black 410 uncle.color = black 411 node.grandparent().color = red 412 tree.insertCase1(node.grandparent()) 413 } else { 414 tree.insertCase4(node) 415 } 416 } 417 418 func (tree *Tree) insertCase4(node *Node) { 419 grandparent := node.grandparent() 420 if node == node.Parent.Right && node.Parent == grandparent.Left { 421 tree.rotateLeft(node.Parent) 422 node = node.Left 423 } else if node == node.Parent.Left && node.Parent == grandparent.Right { 424 tree.rotateRight(node.Parent) 425 node = node.Right 426 } 427 tree.insertCase5(node) 428 } 429 430 func (tree *Tree) insertCase5(node *Node) { 431 node.Parent.color = black 432 grandparent := node.grandparent() 433 grandparent.color = red 434 if node == node.Parent.Left && node.Parent == grandparent.Left { 435 tree.rotateRight(grandparent) 436 } else if node == node.Parent.Right && node.Parent == grandparent.Right { 437 tree.rotateLeft(grandparent) 438 } 439 } 440 441 func (node *Node) maximumNode() *Node { 442 if node == nil { 443 return nil 444 } 445 for node.Right != nil { 446 node = node.Right 447 } 448 return node 449 } 450 451 func (tree *Tree) deleteCase1(node *Node) { 452 if node.Parent == nil { 453 return 454 } 455 tree.deleteCase2(node) 456 } 457 458 func (tree *Tree) deleteCase2(node *Node) { 459 sibling := node.sibling() 460 if nodeColor(sibling) == red { 461 node.Parent.color = red 462 sibling.color = black 463 if node == node.Parent.Left { 464 tree.rotateLeft(node.Parent) 465 } else { 466 tree.rotateRight(node.Parent) 467 } 468 } 469 tree.deleteCase3(node) 470 } 471 472 func (tree *Tree) deleteCase3(node *Node) { 473 sibling := node.sibling() 474 if nodeColor(node.Parent) == black && 475 nodeColor(sibling) == black && 476 nodeColor(sibling.Left) == black && 477 nodeColor(sibling.Right) == black { 478 sibling.color = red 479 tree.deleteCase1(node.Parent) 480 } else { 481 tree.deleteCase4(node) 482 } 483 } 484 485 func (tree *Tree) deleteCase4(node *Node) { 486 sibling := node.sibling() 487 if nodeColor(node.Parent) == red && 488 nodeColor(sibling) == black && 489 nodeColor(sibling.Left) == black && 490 nodeColor(sibling.Right) == black { 491 sibling.color = red 492 node.Parent.color = black 493 } else { 494 tree.deleteCase5(node) 495 } 496 } 497 498 func (tree *Tree) deleteCase5(node *Node) { 499 sibling := node.sibling() 500 if node == node.Parent.Left && 501 nodeColor(sibling) == black && 502 nodeColor(sibling.Left) == red && 503 nodeColor(sibling.Right) == black { 504 sibling.color = red 505 sibling.Left.color = black 506 tree.rotateRight(sibling) 507 } else if node == node.Parent.Right && 508 nodeColor(sibling) == black && 509 nodeColor(sibling.Right) == red && 510 nodeColor(sibling.Left) == black { 511 sibling.color = red 512 sibling.Right.color = black 513 tree.rotateLeft(sibling) 514 } 515 tree.deleteCase6(node) 516 } 517 518 func (tree *Tree) deleteCase6(node *Node) { 519 sibling := node.sibling() 520 sibling.color = nodeColor(node.Parent) 521 node.Parent.color = black 522 if node == node.Parent.Left && nodeColor(sibling.Right) == red { 523 sibling.Right.color = black 524 tree.rotateLeft(node.Parent) 525 } else if nodeColor(sibling.Left) == red { 526 sibling.Left.color = black 527 tree.rotateRight(node.Parent) 528 } 529 } 530 531 func nodeColor(node *Node) color { 532 if node == nil { 533 return black 534 } 535 return node.color 536 }