rbtree.go 14 KB

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