rbtree.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. package rbtree
  2. import (
  3. "math"
  4. )
  5. //
  6. // Public definitions
  7. //
  8. // Item is the object stored in each tree node.
  9. type Item struct {
  10. Key uint32
  11. Value uint32
  12. }
  13. // Allocator is the allocator for nodes in a RBTree.
  14. type Allocator struct {
  15. storage []node
  16. gaps map[uint32]bool
  17. }
  18. // NewAllocator creates a new allocator for RBTree's nodes.
  19. func NewAllocator() *Allocator {
  20. return &Allocator{
  21. storage: []node{},
  22. gaps: map[uint32]bool{},
  23. }
  24. }
  25. // Size returns the currently allocated size.
  26. func (allocator Allocator) Size() int {
  27. return len(allocator.storage)
  28. }
  29. // Clone copies an existing RBTree allocator.
  30. func (allocator *Allocator) Clone() *Allocator {
  31. newAllocator := &Allocator{
  32. storage: make([]node, len(allocator.storage), cap(allocator.storage)),
  33. gaps: map[uint32]bool{},
  34. }
  35. copy(newAllocator.storage, allocator.storage)
  36. for key, val := range allocator.gaps {
  37. newAllocator.gaps[key] = val
  38. }
  39. return newAllocator
  40. }
  41. func (allocator *Allocator) malloc() uint32 {
  42. if len(allocator.gaps) > 0 {
  43. var key uint32
  44. for key = range allocator.gaps {
  45. break
  46. }
  47. delete(allocator.gaps, key)
  48. return key
  49. }
  50. n := len(allocator.storage)
  51. if n == 0 {
  52. // zero is reserved
  53. allocator.storage = append(allocator.storage, node{})
  54. n = 1
  55. }
  56. if n == negativeLimitNode - 1 {
  57. // math.MaxUint32 is reserved
  58. panic("the size of my RBTree allocator has reached the maximum value for uint32, sorry")
  59. }
  60. doAssert(n < negativeLimitNode)
  61. allocator.storage = append(allocator.storage, node{})
  62. return uint32(n)
  63. }
  64. func (allocator *Allocator) free(n uint32) {
  65. _, exists := allocator.gaps[n]
  66. doAssert(!exists)
  67. allocator.storage[n] = node{}
  68. allocator.gaps[n] = true
  69. }
  70. // RBTree is a red-black tree with an API similar to C++ STL's.
  71. //
  72. // The implementation is inspired (read: stolen) from:
  73. // http://en.literateprograms.org/Red-black_tree_(C)#chunk use:private function prototypes.
  74. //
  75. // The code was optimized for the simple integer types of Key and Value.
  76. // The code was further optimized for using allocators.
  77. // Credits: Yaz Saito.
  78. type RBTree struct {
  79. // Root of the tree
  80. root uint32
  81. // The minimum and maximum nodes under the tree.
  82. minNode, maxNode uint32
  83. // Number of nodes under root, including the root
  84. count int32
  85. // Nodes allocator
  86. allocator *Allocator
  87. }
  88. // NewRBTree creates a new red-black binary tree.
  89. func NewRBTree(allocator *Allocator) *RBTree {
  90. return &RBTree{allocator: allocator}
  91. }
  92. func (tree RBTree) storage() []node {
  93. return tree.allocator.storage
  94. }
  95. // Allocator returns the bound nodes allocator.
  96. func (tree RBTree) Allocator() *Allocator {
  97. return tree.allocator
  98. }
  99. // Len returns the number of elements in the tree.
  100. func (tree RBTree) Len() int {
  101. return int(tree.count)
  102. }
  103. // Clone performs a deep copy of the tree.
  104. func (tree RBTree) Clone(allocator *Allocator) *RBTree {
  105. clone := &RBTree{
  106. count: tree.count,
  107. allocator: allocator,
  108. }
  109. nodeMap := map[uint32]uint32{0: 0}
  110. originStorage := tree.storage()
  111. for iter := tree.Min(); !iter.Limit(); iter = iter.Next() {
  112. newNode := allocator.malloc()
  113. cloneNode := &allocator.storage[newNode]
  114. cloneNode.item = *iter.Item()
  115. cloneNode.color = originStorage[iter.node].color
  116. nodeMap[iter.node] = newNode
  117. }
  118. cloneStorage := allocator.storage
  119. for iter := tree.Min(); !iter.Limit(); iter = iter.Next() {
  120. cloneNode := &cloneStorage[nodeMap[iter.node]]
  121. originNode := originStorage[iter.node]
  122. cloneNode.left = nodeMap[originNode.left]
  123. cloneNode.right = nodeMap[originNode.right]
  124. cloneNode.parent = nodeMap[originNode.parent]
  125. }
  126. clone.root = nodeMap[tree.root]
  127. clone.minNode = nodeMap[tree.minNode]
  128. clone.maxNode = nodeMap[tree.maxNode]
  129. return clone
  130. }
  131. // Erase removes all the nodes from the tree.
  132. func (tree *RBTree) Erase() {
  133. for iter := tree.Min(); !iter.Limit(); iter = iter.Next() {
  134. tree.allocator.free(iter.node)
  135. }
  136. tree.root = 0
  137. tree.minNode = 0
  138. tree.maxNode = 0
  139. tree.count = 0
  140. }
  141. // Get is a convenience function for finding an element equal to Key. Returns
  142. // nil if not found.
  143. func (tree RBTree) Get(key uint32) *uint32 {
  144. n, exact := tree.findGE(key)
  145. if exact {
  146. return &tree.storage()[n].item.Value
  147. }
  148. return nil
  149. }
  150. // Min creates an iterator that points to the minimum item in the tree.
  151. // If the tree is empty, returns Limit()
  152. func (tree *RBTree) Min() Iterator {
  153. return Iterator{tree, tree.minNode}
  154. }
  155. // Max creates an iterator that points at the maximum item in the tree.
  156. //
  157. // If the tree is empty, returns NegativeLimit().
  158. func (tree *RBTree) Max() Iterator {
  159. if tree.maxNode == 0 {
  160. return Iterator{tree, negativeLimitNode}
  161. }
  162. return Iterator{tree, tree.maxNode}
  163. }
  164. // Limit creates an iterator that points beyond the maximum item in the tree.
  165. func (tree *RBTree) Limit() Iterator {
  166. return Iterator{tree, 0}
  167. }
  168. // NegativeLimit creates an iterator that points before the minimum item in the tree.
  169. func (tree *RBTree) NegativeLimit() Iterator {
  170. return Iterator{tree, negativeLimitNode}
  171. }
  172. // FindGE finds the smallest element N such that N >= Key, and returns the
  173. // iterator pointing to the element. If no such element is found,
  174. // returns tree.Limit().
  175. func (tree *RBTree) FindGE(key uint32) Iterator {
  176. n, _ := tree.findGE(key)
  177. return Iterator{tree, n}
  178. }
  179. // FindLE finds the largest element N such that N <= Key, and returns the
  180. // iterator pointing to the element. If no such element is found,
  181. // returns iter.NegativeLimit().
  182. func (tree *RBTree) FindLE(key uint32) Iterator {
  183. n, exact := tree.findGE(key)
  184. if exact {
  185. return Iterator{tree, n}
  186. }
  187. if n != 0 {
  188. return Iterator{tree, doPrev(n, tree.storage())}
  189. }
  190. if tree.maxNode == 0 {
  191. return Iterator{tree, negativeLimitNode}
  192. }
  193. return Iterator{tree, tree.maxNode}
  194. }
  195. // Insert an item. If the item is already in the tree, do nothing and
  196. // return false. Else return true.
  197. func (tree *RBTree) Insert(item Item) (bool, Iterator) {
  198. // TODO: delay creating n until it is found to be inserted
  199. n := tree.doInsert(item)
  200. if n == 0 {
  201. return false, Iterator{}
  202. }
  203. alloc := tree.storage()
  204. insN := n
  205. alloc[n].color = red
  206. for true {
  207. // Case 1: N is at the root
  208. if alloc[n].parent == 0 {
  209. alloc[n].color = black
  210. break
  211. }
  212. // Case 2: The parent is black, so the tree already
  213. // satisfies the RB properties
  214. if alloc[alloc[n].parent].color == black {
  215. break
  216. }
  217. // Case 3: parent and uncle are both red.
  218. // Then paint both black and make grandparent red.
  219. grandparent := alloc[alloc[n].parent].parent
  220. var uncle uint32
  221. if isLeftChild(alloc[n].parent, alloc) {
  222. uncle = alloc[grandparent].right
  223. } else {
  224. uncle = alloc[grandparent].left
  225. }
  226. if uncle != 0 && alloc[uncle].color == red {
  227. alloc[alloc[n].parent].color = black
  228. alloc[uncle].color = black
  229. alloc[grandparent].color = red
  230. n = grandparent
  231. continue
  232. }
  233. // Case 4: parent is red, uncle is black (1)
  234. if isRightChild(n, alloc) && isLeftChild(alloc[n].parent, alloc) {
  235. tree.rotateLeft(alloc[n].parent)
  236. n = alloc[n].left
  237. continue
  238. }
  239. if isLeftChild(n, alloc) && isRightChild(alloc[n].parent, alloc) {
  240. tree.rotateRight(alloc[n].parent)
  241. n = alloc[n].right
  242. continue
  243. }
  244. // Case 5: parent is read, uncle is black (2)
  245. alloc[alloc[n].parent].color = black
  246. alloc[grandparent].color = red
  247. if isLeftChild(n, alloc) {
  248. tree.rotateRight(grandparent)
  249. } else {
  250. tree.rotateLeft(grandparent)
  251. }
  252. break
  253. }
  254. return true, Iterator{tree, insN}
  255. }
  256. // DeleteWithKey deletes an item with the given Key. Returns true iff the item was
  257. // found.
  258. func (tree *RBTree) DeleteWithKey(key uint32) bool {
  259. n, exact := tree.findGE(key)
  260. if exact {
  261. tree.doDelete(n)
  262. return true
  263. }
  264. return false
  265. }
  266. // DeleteWithIterator deletes the current item.
  267. //
  268. // REQUIRES: !iter.Limit() && !iter.NegativeLimit()
  269. func (tree *RBTree) DeleteWithIterator(iter Iterator) {
  270. doAssert(!iter.Limit() && !iter.NegativeLimit())
  271. tree.doDelete(iter.node)
  272. }
  273. // Iterator allows scanning tree elements in sort order.
  274. //
  275. // Iterator invalidation rule is the same as C++ std::map<>'s. That
  276. // is, if you delete the element that an iterator points to, the
  277. // iterator becomes invalid. For other operation types, the iterator
  278. // remains valid.
  279. type Iterator struct {
  280. tree *RBTree
  281. node uint32
  282. }
  283. // Equal checks for the underlying nodes equality.
  284. func (iter Iterator) Equal(other Iterator) bool {
  285. return iter.node == other.node
  286. }
  287. // Limit checks if the iterator points beyond the max element in the tree.
  288. func (iter Iterator) Limit() bool {
  289. return iter.node == 0
  290. }
  291. // Min checks if the iterator points to the minimum element in the tree.
  292. func (iter Iterator) Min() bool {
  293. return iter.node == iter.tree.minNode
  294. }
  295. // Max checks if the iterator points to the maximum element in the tree.
  296. func (iter Iterator) Max() bool {
  297. return iter.node == iter.tree.maxNode
  298. }
  299. // NegativeLimit checks if the iterator points before the minimum element in the tree.
  300. func (iter Iterator) NegativeLimit() bool {
  301. return iter.node == negativeLimitNode
  302. }
  303. // Item returns the current element. Allows mutating the node
  304. // (key to be changed with care!).
  305. //
  306. // The result is nil if iter.Limit() || iter.NegativeLimit().
  307. func (iter Iterator) Item() *Item {
  308. if iter.Limit() || iter.NegativeLimit() {
  309. return nil
  310. }
  311. return &iter.tree.storage()[iter.node].item
  312. }
  313. // Next creates a new iterator that points to the successor of the current element.
  314. //
  315. // REQUIRES: !iter.Limit()
  316. func (iter Iterator) Next() Iterator {
  317. doAssert(!iter.Limit())
  318. if iter.NegativeLimit() {
  319. return Iterator{iter.tree, iter.tree.minNode}
  320. }
  321. return Iterator{iter.tree, doNext(iter.node, iter.tree.storage())}
  322. }
  323. // Prev creates a new iterator that points to the predecessor of the current
  324. // node.
  325. //
  326. // REQUIRES: !iter.NegativeLimit()
  327. func (iter Iterator) Prev() Iterator {
  328. doAssert(!iter.NegativeLimit())
  329. if !iter.Limit() {
  330. return Iterator{iter.tree, doPrev(iter.node, iter.tree.storage())}
  331. }
  332. if iter.tree.maxNode == 0 {
  333. return Iterator{iter.tree, negativeLimitNode}
  334. }
  335. return Iterator{iter.tree, iter.tree.maxNode}
  336. }
  337. func doAssert(b bool) {
  338. if !b {
  339. panic("rbtree internal assertion failed")
  340. }
  341. }
  342. const (
  343. red = false
  344. black = true
  345. negativeLimitNode = math.MaxUint32
  346. )
  347. type node struct {
  348. item Item
  349. parent, left, right uint32
  350. color bool // black or red
  351. }
  352. //
  353. // Internal node attribute accessors
  354. //
  355. func getColor(n uint32, allocator []node) bool {
  356. if n == 0 {
  357. return black
  358. }
  359. return allocator[n].color
  360. }
  361. func isLeftChild(n uint32, allocator []node) bool {
  362. return n == allocator[allocator[n].parent].left
  363. }
  364. func isRightChild(n uint32, allocator []node) bool {
  365. return n == allocator[allocator[n].parent].right
  366. }
  367. func sibling(n uint32, allocator []node) uint32 {
  368. doAssert(allocator[n].parent != 0)
  369. if isLeftChild(n, allocator) {
  370. return allocator[allocator[n].parent].right
  371. }
  372. return allocator[allocator[n].parent].left
  373. }
  374. // Return the minimum node that's larger than N. Return nil if no such
  375. // node is found.
  376. func doNext(n uint32, allocator []node) uint32 {
  377. if allocator[n].right != 0 {
  378. m := allocator[n].right
  379. for allocator[m].left != 0 {
  380. m = allocator[m].left
  381. }
  382. return m
  383. }
  384. for n != 0 {
  385. p := allocator[n].parent
  386. if p == 0 {
  387. return 0
  388. }
  389. if isLeftChild(n, allocator) {
  390. return p
  391. }
  392. n = p
  393. }
  394. return 0
  395. }
  396. // Return the maximum node that's smaller than N. Return nil if no
  397. // such node is found.
  398. func doPrev(n uint32, allocator []node) uint32 {
  399. if allocator[n].left != 0 {
  400. return maxPredecessor(n, allocator)
  401. }
  402. for n != 0 {
  403. p := allocator[n].parent
  404. if p == 0 {
  405. break
  406. }
  407. if isRightChild(n, allocator) {
  408. return p
  409. }
  410. n = p
  411. }
  412. return negativeLimitNode
  413. }
  414. // Return the predecessor of "n".
  415. func maxPredecessor(n uint32, allocator []node) uint32 {
  416. doAssert(allocator[n].left != 0)
  417. m := allocator[n].left
  418. for allocator[m].right != 0 {
  419. m = allocator[m].right
  420. }
  421. return m
  422. }
  423. //
  424. // Tree methods
  425. //
  426. //
  427. // Private methods
  428. //
  429. func (tree *RBTree) recomputeMinNode() {
  430. alloc := tree.storage()
  431. tree.minNode = tree.root
  432. if tree.minNode != 0 {
  433. for alloc[tree.minNode].left != 0 {
  434. tree.minNode = alloc[tree.minNode].left
  435. }
  436. }
  437. }
  438. func (tree *RBTree) recomputeMaxNode() {
  439. alloc := tree.storage()
  440. tree.maxNode = tree.root
  441. if tree.maxNode != 0 {
  442. for alloc[tree.maxNode].right != 0 {
  443. tree.maxNode = alloc[tree.maxNode].right
  444. }
  445. }
  446. }
  447. func (tree *RBTree) maybeSetMinNode(n uint32) {
  448. alloc := tree.storage()
  449. if tree.minNode == 0 {
  450. tree.minNode = n
  451. tree.maxNode = n
  452. } else if alloc[n].item.Key < alloc[tree.minNode].item.Key {
  453. tree.minNode = n
  454. }
  455. }
  456. func (tree *RBTree) maybeSetMaxNode(n uint32) {
  457. alloc := tree.storage()
  458. if tree.maxNode == 0 {
  459. tree.minNode = n
  460. tree.maxNode = n
  461. } else if alloc[n].item.Key > alloc[tree.maxNode].item.Key {
  462. tree.maxNode = n
  463. }
  464. }
  465. // Try inserting "item" into the tree. Return nil if the item is
  466. // already in the tree. Otherwise return a new (leaf) node.
  467. func (tree *RBTree) doInsert(item Item) uint32 {
  468. if tree.root == 0 {
  469. n := tree.allocator.malloc()
  470. tree.storage()[n].item = item
  471. tree.root = n
  472. tree.minNode = n
  473. tree.maxNode = n
  474. tree.count++
  475. return n
  476. }
  477. parent := tree.root
  478. storage := tree.storage()
  479. for true {
  480. parentNode := storage[parent]
  481. comp := int(item.Key) - int(parentNode.item.Key)
  482. if comp == 0 {
  483. return 0
  484. } else if comp < 0 {
  485. if parentNode.left == 0 {
  486. n := tree.allocator.malloc()
  487. storage = tree.storage()
  488. newNode := &storage[n]
  489. newNode.item = item
  490. newNode.parent = parent
  491. storage[parent].left = n
  492. tree.count++
  493. tree.maybeSetMinNode(n)
  494. return n
  495. }
  496. parent = parentNode.left
  497. } else {
  498. if parentNode.right == 0 {
  499. n := tree.allocator.malloc()
  500. storage = tree.storage()
  501. newNode := &storage[n]
  502. newNode.item = item
  503. newNode.parent = parent
  504. storage[parent].right = n
  505. tree.count++
  506. tree.maybeSetMaxNode(n)
  507. return n
  508. }
  509. parent = parentNode.right
  510. }
  511. }
  512. panic("should not reach here")
  513. }
  514. // Find a node whose item >= Key. The 2nd return Value is true iff the
  515. // node.item==Key. Returns (nil, false) if all nodes in the tree are <
  516. // Key.
  517. func (tree RBTree) findGE(key uint32) (uint32, bool) {
  518. alloc := tree.storage()
  519. n := tree.root
  520. for true {
  521. if n == 0 {
  522. return 0, false
  523. }
  524. comp := int(key) - int(alloc[n].item.Key)
  525. if comp == 0 {
  526. return n, true
  527. } else if comp < 0 {
  528. if alloc[n].left != 0 {
  529. n = alloc[n].left
  530. } else {
  531. return n, false
  532. }
  533. } else {
  534. if alloc[n].right != 0 {
  535. n = alloc[n].right
  536. } else {
  537. succ := doNext(n, alloc)
  538. if succ == 0 {
  539. return 0, false
  540. }
  541. return succ, key == alloc[succ].item.Key
  542. }
  543. }
  544. }
  545. panic("should not reach here")
  546. }
  547. // Delete N from the tree.
  548. func (tree *RBTree) doDelete(n uint32) {
  549. alloc := tree.storage()
  550. if alloc[n].left != 0 && alloc[n].right != 0 {
  551. pred := maxPredecessor(n, alloc)
  552. tree.swapNodes(n, pred)
  553. }
  554. doAssert(alloc[n].left == 0 || alloc[n].right == 0)
  555. child := alloc[n].right
  556. if child == 0 {
  557. child = alloc[n].left
  558. }
  559. if alloc[n].color == black {
  560. alloc[n].color = getColor(child, alloc)
  561. tree.deleteCase1(n)
  562. }
  563. tree.replaceNode(n, child)
  564. if alloc[n].parent == 0 && child != 0 {
  565. alloc[child].color = black
  566. }
  567. tree.allocator.free(n)
  568. tree.count--
  569. if tree.count == 0 {
  570. tree.minNode = 0
  571. tree.maxNode = 0
  572. } else {
  573. if tree.minNode == n {
  574. tree.recomputeMinNode()
  575. }
  576. if tree.maxNode == n {
  577. tree.recomputeMaxNode()
  578. }
  579. }
  580. }
  581. // Move n to the pred's place, and vice versa
  582. //
  583. func (tree *RBTree) swapNodes(n, pred uint32) {
  584. doAssert(pred != n)
  585. alloc := tree.storage()
  586. isLeft := isLeftChild(pred, alloc)
  587. tmp := alloc[pred]
  588. tree.replaceNode(n, pred)
  589. alloc[pred].color = alloc[n].color
  590. if tmp.parent == n {
  591. // swap the positions of n and pred
  592. if isLeft {
  593. alloc[pred].left = n
  594. alloc[pred].right = alloc[n].right
  595. if alloc[pred].right != 0 {
  596. alloc[alloc[pred].right].parent = pred
  597. }
  598. } else {
  599. alloc[pred].left = alloc[n].left
  600. if alloc[pred].left != 0 {
  601. alloc[alloc[pred].left].parent = pred
  602. }
  603. alloc[pred].right = n
  604. }
  605. alloc[n].item = tmp.item
  606. alloc[n].parent = pred
  607. alloc[n].left = tmp.left
  608. if alloc[n].left != 0 {
  609. alloc[alloc[n].left].parent = n
  610. }
  611. alloc[n].right = tmp.right
  612. if alloc[n].right != 0 {
  613. alloc[alloc[n].right].parent = n
  614. }
  615. } else {
  616. alloc[pred].left = alloc[n].left
  617. if alloc[pred].left != 0 {
  618. alloc[alloc[pred].left].parent = pred
  619. }
  620. alloc[pred].right = alloc[n].right
  621. if alloc[pred].right != 0 {
  622. alloc[alloc[pred].right].parent = pred
  623. }
  624. if isLeft {
  625. alloc[tmp.parent].left = n
  626. } else {
  627. alloc[tmp.parent].right = n
  628. }
  629. alloc[n].item = tmp.item
  630. alloc[n].parent = tmp.parent
  631. alloc[n].left = tmp.left
  632. if alloc[n].left != 0 {
  633. alloc[alloc[n].left].parent = n
  634. }
  635. alloc[n].right = tmp.right
  636. if alloc[n].right != 0 {
  637. alloc[alloc[n].right].parent = n
  638. }
  639. }
  640. alloc[n].color = tmp.color
  641. }
  642. func (tree *RBTree) deleteCase1(n uint32) {
  643. alloc := tree.storage()
  644. for true {
  645. if alloc[n].parent != 0 {
  646. if getColor(sibling(n, alloc), alloc) == red {
  647. alloc[alloc[n].parent].color = red
  648. alloc[sibling(n, alloc)].color = black
  649. if n == alloc[alloc[n].parent].left {
  650. tree.rotateLeft(alloc[n].parent)
  651. } else {
  652. tree.rotateRight(alloc[n].parent)
  653. }
  654. }
  655. if getColor(alloc[n].parent, alloc) == black &&
  656. getColor(sibling(n, alloc), alloc) == black &&
  657. getColor(alloc[sibling(n, alloc)].left, alloc) == black &&
  658. getColor(alloc[sibling(n, alloc)].right, alloc) == black {
  659. alloc[sibling(n, alloc)].color = red
  660. n = alloc[n].parent
  661. continue
  662. } else {
  663. // case 4
  664. if getColor(alloc[n].parent, alloc) == red &&
  665. getColor(sibling(n, alloc), alloc) == black &&
  666. getColor(alloc[sibling(n, alloc)].left, alloc) == black &&
  667. getColor(alloc[sibling(n, alloc)].right, alloc) == black {
  668. alloc[sibling(n, alloc)].color = red
  669. alloc[alloc[n].parent].color = black
  670. } else {
  671. tree.deleteCase5(n)
  672. }
  673. }
  674. }
  675. break
  676. }
  677. }
  678. func (tree *RBTree) deleteCase5(n uint32) {
  679. alloc := tree.storage()
  680. if n == alloc[alloc[n].parent].left &&
  681. getColor(sibling(n, alloc), alloc) == black &&
  682. getColor(alloc[sibling(n, alloc)].left, alloc) == red &&
  683. getColor(alloc[sibling(n, alloc)].right, alloc) == black {
  684. alloc[sibling(n, alloc)].color = red
  685. alloc[alloc[sibling(n, alloc)].left].color = black
  686. tree.rotateRight(sibling(n, alloc))
  687. } else if n == alloc[alloc[n].parent].right &&
  688. getColor(sibling(n, alloc), alloc) == black &&
  689. getColor(alloc[sibling(n, alloc)].right, alloc) == red &&
  690. getColor(alloc[sibling(n, alloc)].left, alloc) == black {
  691. alloc[sibling(n, alloc)].color = red
  692. alloc[alloc[sibling(n, alloc)].right].color = black
  693. tree.rotateLeft(sibling(n, alloc))
  694. }
  695. // case 6
  696. alloc[sibling(n, alloc)].color = getColor(alloc[n].parent, alloc)
  697. alloc[alloc[n].parent].color = black
  698. if n == alloc[alloc[n].parent].left {
  699. doAssert(getColor(alloc[sibling(n, alloc)].right, alloc) == red)
  700. alloc[alloc[sibling(n, alloc)].right].color = black
  701. tree.rotateLeft(alloc[n].parent)
  702. } else {
  703. doAssert(getColor(alloc[sibling(n, alloc)].left, alloc) == red)
  704. alloc[alloc[sibling(n, alloc)].left].color = black
  705. tree.rotateRight(alloc[n].parent)
  706. }
  707. }
  708. func (tree *RBTree) replaceNode(oldn, newn uint32) {
  709. alloc := tree.storage()
  710. if alloc[oldn].parent == 0 {
  711. tree.root = newn
  712. } else {
  713. if oldn == alloc[alloc[oldn].parent].left {
  714. alloc[alloc[oldn].parent].left = newn
  715. } else {
  716. alloc[alloc[oldn].parent].right = newn
  717. }
  718. }
  719. if newn != 0 {
  720. alloc[newn].parent = alloc[oldn].parent
  721. }
  722. }
  723. /*
  724. X Y
  725. A Y => X C
  726. B C A B
  727. */
  728. func (tree *RBTree) rotateLeft(x uint32) {
  729. alloc := tree.storage()
  730. y := alloc[x].right
  731. alloc[x].right = alloc[y].left
  732. if alloc[y].left != 0 {
  733. alloc[alloc[y].left].parent = x
  734. }
  735. alloc[y].parent = alloc[x].parent
  736. if alloc[x].parent == 0 {
  737. tree.root = y
  738. } else {
  739. if isLeftChild(x, alloc) {
  740. alloc[alloc[x].parent].left = y
  741. } else {
  742. alloc[alloc[x].parent].right = y
  743. }
  744. }
  745. alloc[y].left = x
  746. alloc[x].parent = y
  747. }
  748. /*
  749. Y X
  750. X C => A Y
  751. A B B C
  752. */
  753. func (tree *RBTree) rotateRight(y uint32) {
  754. alloc := tree.storage()
  755. x := alloc[y].left
  756. // Move "B"
  757. alloc[y].left = alloc[x].right
  758. if alloc[x].right != 0 {
  759. alloc[alloc[x].right].parent = y
  760. }
  761. alloc[x].parent = alloc[y].parent
  762. if alloc[y].parent == 0 {
  763. tree.root = x
  764. } else {
  765. if isLeftChild(y, alloc) {
  766. alloc[alloc[y].parent].left = x
  767. } else {
  768. alloc[alloc[y].parent].right = x
  769. }
  770. }
  771. alloc[x].right = y
  772. alloc[y].parent = x
  773. }