rbtree.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. package rbtree
  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. insN := 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, insN}
  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(other Iterator) bool {
  172. return iter.node == other.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. }
  367. parent = parent.left
  368. } else {
  369. if parent.right == nil {
  370. n := &node{item: item, parent: parent}
  371. parent.right = n
  372. root.count++
  373. root.maybeSetMaxNode(n)
  374. return n
  375. }
  376. parent = parent.right
  377. }
  378. }
  379. panic("should not reach here")
  380. }
  381. // Find a node whose item >= Key. The 2nd return Value is true iff the
  382. // node.item==Key. Returns (nil, false) if all nodes in the tree are <
  383. // Key.
  384. func (root *RBTree) findGE(key int) (*node, bool) {
  385. n := root.root
  386. for true {
  387. if n == nil {
  388. return nil, false
  389. }
  390. comp := key - n.item.Key
  391. if comp == 0 {
  392. return n, true
  393. } else if comp < 0 {
  394. if n.left != nil {
  395. n = n.left
  396. } else {
  397. return n, false
  398. }
  399. } else {
  400. if n.right != nil {
  401. n = n.right
  402. } else {
  403. succ := n.doNext()
  404. if succ == nil {
  405. return nil, false
  406. }
  407. return succ, key == succ.item.Key
  408. }
  409. }
  410. }
  411. panic("should not reach here")
  412. }
  413. // Delete N from the tree.
  414. func (root *RBTree) doDelete(n *node) {
  415. if n.left != nil && n.right != nil {
  416. pred := maxPredecessor(n)
  417. root.swapNodes(n, pred)
  418. }
  419. doAssert(n.left == nil || n.right == nil)
  420. child := n.right
  421. if child == nil {
  422. child = n.left
  423. }
  424. if n.color == black {
  425. n.color = getColor(child)
  426. root.deleteCase1(n)
  427. }
  428. root.replaceNode(n, child)
  429. if n.parent == nil && child != nil {
  430. child.color = black
  431. }
  432. root.count--
  433. if root.count == 0 {
  434. root.minNode = nil
  435. root.maxNode = nil
  436. } else {
  437. if root.minNode == n {
  438. root.recomputeMinNode()
  439. }
  440. if root.maxNode == n {
  441. root.recomputeMaxNode()
  442. }
  443. }
  444. }
  445. // Move n to the pred's place, and vice versa
  446. //
  447. func (root *RBTree) swapNodes(n, pred *node) {
  448. doAssert(pred != n)
  449. isLeft := pred.isLeftChild()
  450. tmp := *pred
  451. root.replaceNode(n, pred)
  452. pred.color = n.color
  453. if tmp.parent == n {
  454. // swap the positions of n and pred
  455. if isLeft {
  456. pred.left = n
  457. pred.right = n.right
  458. if pred.right != nil {
  459. pred.right.parent = pred
  460. }
  461. } else {
  462. pred.left = n.left
  463. if pred.left != nil {
  464. pred.left.parent = pred
  465. }
  466. pred.right = n
  467. }
  468. n.item = tmp.item
  469. n.parent = pred
  470. n.left = tmp.left
  471. if n.left != nil {
  472. n.left.parent = n
  473. }
  474. n.right = tmp.right
  475. if n.right != nil {
  476. n.right.parent = n
  477. }
  478. } else {
  479. pred.left = n.left
  480. if pred.left != nil {
  481. pred.left.parent = pred
  482. }
  483. pred.right = n.right
  484. if pred.right != nil {
  485. pred.right.parent = pred
  486. }
  487. if isLeft {
  488. tmp.parent.left = n
  489. } else {
  490. tmp.parent.right = n
  491. }
  492. n.item = tmp.item
  493. n.parent = tmp.parent
  494. n.left = tmp.left
  495. if n.left != nil {
  496. n.left.parent = n
  497. }
  498. n.right = tmp.right
  499. if n.right != nil {
  500. n.right.parent = n
  501. }
  502. }
  503. n.color = tmp.color
  504. }
  505. func (root *RBTree) deleteCase1(n *node) {
  506. for true {
  507. if n.parent != nil {
  508. if getColor(n.sibling()) == red {
  509. n.parent.color = red
  510. n.sibling().color = black
  511. if n == n.parent.left {
  512. root.rotateLeft(n.parent)
  513. } else {
  514. root.rotateRight(n.parent)
  515. }
  516. }
  517. if getColor(n.parent) == black &&
  518. getColor(n.sibling()) == black &&
  519. getColor(n.sibling().left) == black &&
  520. getColor(n.sibling().right) == black {
  521. n.sibling().color = red
  522. n = n.parent
  523. continue
  524. } else {
  525. // case 4
  526. if getColor(n.parent) == red &&
  527. getColor(n.sibling()) == black &&
  528. getColor(n.sibling().left) == black &&
  529. getColor(n.sibling().right) == black {
  530. n.sibling().color = red
  531. n.parent.color = black
  532. } else {
  533. root.deleteCase5(n)
  534. }
  535. }
  536. }
  537. break
  538. }
  539. }
  540. func (root *RBTree) deleteCase5(n *node) {
  541. if n == n.parent.left &&
  542. getColor(n.sibling()) == black &&
  543. getColor(n.sibling().left) == red &&
  544. getColor(n.sibling().right) == black {
  545. n.sibling().color = red
  546. n.sibling().left.color = black
  547. root.rotateRight(n.sibling())
  548. } else if n == n.parent.right &&
  549. getColor(n.sibling()) == black &&
  550. getColor(n.sibling().right) == red &&
  551. getColor(n.sibling().left) == black {
  552. n.sibling().color = red
  553. n.sibling().right.color = black
  554. root.rotateLeft(n.sibling())
  555. }
  556. // case 6
  557. n.sibling().color = getColor(n.parent)
  558. n.parent.color = black
  559. if n == n.parent.left {
  560. doAssert(getColor(n.sibling().right) == red)
  561. n.sibling().right.color = black
  562. root.rotateLeft(n.parent)
  563. } else {
  564. doAssert(getColor(n.sibling().left) == red)
  565. n.sibling().left.color = black
  566. root.rotateRight(n.parent)
  567. }
  568. }
  569. func (root *RBTree) replaceNode(oldn, newn *node) {
  570. if oldn.parent == nil {
  571. root.root = newn
  572. } else {
  573. if oldn == oldn.parent.left {
  574. oldn.parent.left = newn
  575. } else {
  576. oldn.parent.right = newn
  577. }
  578. }
  579. if newn != nil {
  580. newn.parent = oldn.parent
  581. }
  582. }
  583. /*
  584. X Y
  585. A Y => X C
  586. B C A B
  587. */
  588. func (root *RBTree) rotateLeft(x *node) {
  589. y := x.right
  590. x.right = y.left
  591. if y.left != nil {
  592. y.left.parent = x
  593. }
  594. y.parent = x.parent
  595. if x.parent == nil {
  596. root.root = y
  597. } else {
  598. if x.isLeftChild() {
  599. x.parent.left = y
  600. } else {
  601. x.parent.right = y
  602. }
  603. }
  604. y.left = x
  605. x.parent = y
  606. }
  607. /*
  608. Y X
  609. X C => A Y
  610. A B B C
  611. */
  612. func (root *RBTree) rotateRight(y *node) {
  613. x := y.left
  614. // Move "B"
  615. y.left = x.right
  616. if x.right != nil {
  617. x.right.parent = y
  618. }
  619. x.parent = y.parent
  620. if y.parent == nil {
  621. root.root = x
  622. } else {
  623. if y.isLeftChild() {
  624. y.parent.left = x
  625. } else {
  626. y.parent.right = x
  627. }
  628. }
  629. x.right = y
  630. y.parent = x
  631. }
  632. func init() {
  633. negativeLimitNode = &node{}
  634. }