gitee.com/quant1x/gox@v1.7.6/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.Root = nil 268 tree.size = 0 269 } 270 271 // String returns a string representation of container 272 func (tree *Tree) String() string { 273 str := "RedBlackTree\n" 274 if !tree.Empty() { 275 output(tree.Root, "", true, &str) 276 } 277 return str 278 } 279 280 func (node *Node) String() string { 281 return fmt.Sprintf("%v", node.Key) 282 } 283 284 func output(node *Node, prefix string, isTail bool, str *string) { 285 if node.Right != nil { 286 newPrefix := prefix 287 if isTail { 288 newPrefix += "│ " 289 } else { 290 newPrefix += " " 291 } 292 output(node.Right, newPrefix, false, str) 293 } 294 *str += prefix 295 if isTail { 296 *str += "└── " 297 } else { 298 *str += "┌── " 299 } 300 *str += node.String() + "\n" 301 if node.Left != nil { 302 newPrefix := prefix 303 if isTail { 304 newPrefix += " " 305 } else { 306 newPrefix += "│ " 307 } 308 output(node.Left, newPrefix, true, str) 309 } 310 } 311 312 func (tree *Tree) lookup(key interface{}) *Node { 313 node := tree.Root 314 for node != nil { 315 compare := tree.Comparator(key, node.Key) 316 switch { 317 case compare == 0: 318 return node 319 case compare < 0: 320 node = node.Left 321 case compare > 0: 322 node = node.Right 323 } 324 } 325 return nil 326 } 327 328 func (node *Node) grandparent() *Node { 329 if node != nil && node.Parent != nil { 330 return node.Parent.Parent 331 } 332 return nil 333 } 334 335 func (node *Node) uncle() *Node { 336 if node == nil || node.Parent == nil || node.Parent.Parent == nil { 337 return nil 338 } 339 return node.Parent.sibling() 340 } 341 342 func (node *Node) sibling() *Node { 343 if node == nil || node.Parent == nil { 344 return nil 345 } 346 if node == node.Parent.Left { 347 return node.Parent.Right 348 } 349 return node.Parent.Left 350 } 351 352 func (tree *Tree) rotateLeft(node *Node) { 353 right := node.Right 354 tree.replaceNode(node, right) 355 node.Right = right.Left 356 if right.Left != nil { 357 right.Left.Parent = node 358 } 359 right.Left = node 360 node.Parent = right 361 } 362 363 func (tree *Tree) rotateRight(node *Node) { 364 left := node.Left 365 tree.replaceNode(node, left) 366 node.Left = left.Right 367 if left.Right != nil { 368 left.Right.Parent = node 369 } 370 left.Right = node 371 node.Parent = left 372 } 373 374 func (tree *Tree) replaceNode(old *Node, new *Node) { 375 if old.Parent == nil { 376 tree.Root = new 377 } else { 378 if old == old.Parent.Left { 379 old.Parent.Left = new 380 } else { 381 old.Parent.Right = new 382 } 383 } 384 if new != nil { 385 new.Parent = old.Parent 386 } 387 } 388 389 func (tree *Tree) insertCase1(node *Node) { 390 if node.Parent == nil { 391 node.color = black 392 } else { 393 tree.insertCase2(node) 394 } 395 } 396 397 func (tree *Tree) insertCase2(node *Node) { 398 if nodeColor(node.Parent) == black { 399 return 400 } 401 tree.insertCase3(node) 402 } 403 404 func (tree *Tree) insertCase3(node *Node) { 405 uncle := node.uncle() 406 if nodeColor(uncle) == red { 407 node.Parent.color = black 408 uncle.color = black 409 node.grandparent().color = red 410 tree.insertCase1(node.grandparent()) 411 } else { 412 tree.insertCase4(node) 413 } 414 } 415 416 func (tree *Tree) insertCase4(node *Node) { 417 grandparent := node.grandparent() 418 if node == node.Parent.Right && node.Parent == grandparent.Left { 419 tree.rotateLeft(node.Parent) 420 node = node.Left 421 } else if node == node.Parent.Left && node.Parent == grandparent.Right { 422 tree.rotateRight(node.Parent) 423 node = node.Right 424 } 425 tree.insertCase5(node) 426 } 427 428 func (tree *Tree) insertCase5(node *Node) { 429 node.Parent.color = black 430 grandparent := node.grandparent() 431 grandparent.color = red 432 if node == node.Parent.Left && node.Parent == grandparent.Left { 433 tree.rotateRight(grandparent) 434 } else if node == node.Parent.Right && node.Parent == grandparent.Right { 435 tree.rotateLeft(grandparent) 436 } 437 } 438 439 func (node *Node) maximumNode() *Node { 440 if node == nil { 441 return nil 442 } 443 for node.Right != nil { 444 node = node.Right 445 } 446 return node 447 } 448 449 func (tree *Tree) deleteCase1(node *Node) { 450 if node.Parent == nil { 451 return 452 } 453 tree.deleteCase2(node) 454 } 455 456 func (tree *Tree) deleteCase2(node *Node) { 457 sibling := node.sibling() 458 if nodeColor(sibling) == red { 459 node.Parent.color = red 460 sibling.color = black 461 if node == node.Parent.Left { 462 tree.rotateLeft(node.Parent) 463 } else { 464 tree.rotateRight(node.Parent) 465 } 466 } 467 tree.deleteCase3(node) 468 } 469 470 func (tree *Tree) deleteCase3(node *Node) { 471 sibling := node.sibling() 472 if nodeColor(node.Parent) == black && 473 nodeColor(sibling) == black && 474 nodeColor(sibling.Left) == black && 475 nodeColor(sibling.Right) == black { 476 sibling.color = red 477 tree.deleteCase1(node.Parent) 478 } else { 479 tree.deleteCase4(node) 480 } 481 } 482 483 func (tree *Tree) deleteCase4(node *Node) { 484 sibling := node.sibling() 485 if nodeColor(node.Parent) == red && 486 nodeColor(sibling) == black && 487 nodeColor(sibling.Left) == black && 488 nodeColor(sibling.Right) == black { 489 sibling.color = red 490 node.Parent.color = black 491 } else { 492 tree.deleteCase5(node) 493 } 494 } 495 496 func (tree *Tree) deleteCase5(node *Node) { 497 sibling := node.sibling() 498 if node == node.Parent.Left && 499 nodeColor(sibling) == black && 500 nodeColor(sibling.Left) == red && 501 nodeColor(sibling.Right) == black { 502 sibling.color = red 503 sibling.Left.color = black 504 tree.rotateRight(sibling) 505 } else if node == node.Parent.Right && 506 nodeColor(sibling) == black && 507 nodeColor(sibling.Right) == red && 508 nodeColor(sibling.Left) == black { 509 sibling.color = red 510 sibling.Right.color = black 511 tree.rotateLeft(sibling) 512 } 513 tree.deleteCase6(node) 514 } 515 516 func (tree *Tree) deleteCase6(node *Node) { 517 sibling := node.sibling() 518 sibling.color = nodeColor(node.Parent) 519 node.Parent.color = black 520 if node == node.Parent.Left && nodeColor(sibling.Right) == red { 521 sibling.Right.color = black 522 tree.rotateLeft(node.Parent) 523 } else if nodeColor(sibling.Left) == red { 524 sibling.Left.color = black 525 tree.rotateRight(node.Parent) 526 } 527 } 528 529 func nodeColor(node *Node) color { 530 if node == nil { 531 return black 532 } 533 return node.color 534 }