rbtree.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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. // Len returns the number of elements in the tree.
  27. func (root *RBTree) Len() int {
  28. return root.count
  29. }
  30. // Get is a convenience function for finding an element equal to Key. Returns
  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. // Min creates an iterator that points to the minimum item in the tree.
  40. // If the tree is empty, returns Limit()
  41. func (root *RBTree) Min() Iterator {
  42. return Iterator{root, root.minNode}
  43. }
  44. // Max creates an iterator that points at the maximum item in the tree.
  45. //
  46. // If the tree is empty, returns 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. // Limit creates an iterator that points beyond the maximum item in the tree.
  54. func (root *RBTree) Limit() Iterator {
  55. return Iterator{root, nil}
  56. }
  57. // NegativeLimit creates an iterator that points before the minimum item in the tree.
  58. func (root *RBTree) NegativeLimit() Iterator {
  59. return Iterator{root, negativeLimitNode}
  60. }
  61. // FindGE finds the smallest element N such that N >= Key, and returns the
  62. // iterator pointing to the element. If no such element is found,
  63. // returns root.Limit().
  64. func (root *RBTree) FindGE(key int) Iterator {
  65. n, _ := root.findGE(key)
  66. return Iterator{root, n}
  67. }
  68. // FindLE finds the largest element N such that N <= Key, and returns the
  69. // iterator pointing to the element. If no such element is found,
  70. // returns 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. // DeleteWithKey deletes an item with the given Key. Returns 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. // DeleteWithIterator deletes 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. // Equal checks for the underlying nodes equality.
  172. func (iter Iterator) Equal(other Iterator) bool {
  173. return iter.node == other.node
  174. }
  175. // Limit checks if the iterator points beyond the max element in the tree.
  176. func (iter Iterator) Limit() bool {
  177. return iter.node == nil
  178. }
  179. // Min checks if the iterator points to the minimum element in the tree.
  180. func (iter Iterator) Min() bool {
  181. return iter.node == iter.root.minNode
  182. }
  183. // Max checks if the iterator points to the maximum element in the tree.
  184. func (iter Iterator) Max() bool {
  185. return iter.node == iter.root.maxNode
  186. }
  187. // NegativeLimit checks if the iterator points before the minimum element in the tree.
  188. func (iter Iterator) NegativeLimit() bool {
  189. return iter.node == negativeLimitNode
  190. }
  191. // Item returns the current element. Allows mutating the node
  192. // (key to be changed with care!).
  193. //
  194. // REQUIRES: !iter.Limit() && !iter.NegativeLimit()
  195. func (iter Iterator) Item() *Item {
  196. return &iter.node.item
  197. }
  198. // Next creates a new iterator that points to the successor of the current element.
  199. //
  200. // REQUIRES: !iter.Limit()
  201. func (iter Iterator) Next() Iterator {
  202. doAssert(!iter.Limit())
  203. if iter.NegativeLimit() {
  204. return Iterator{iter.root, iter.root.minNode}
  205. }
  206. return Iterator{iter.root, iter.node.doNext()}
  207. }
  208. // Prev creates a new iterator that points to the predecessor of the current
  209. // node.
  210. //
  211. // REQUIRES: !iter.NegativeLimit()
  212. func (iter Iterator) Prev() Iterator {
  213. doAssert(!iter.NegativeLimit())
  214. if !iter.Limit() {
  215. return Iterator{iter.root, iter.node.doPrev()}
  216. }
  217. if iter.root.maxNode == nil {
  218. return Iterator{iter.root, negativeLimitNode}
  219. }
  220. return Iterator{iter.root, iter.root.maxNode}
  221. }
  222. func doAssert(b bool) {
  223. if !b {
  224. panic("rbtree internal assertion failed")
  225. }
  226. }
  227. const red = iota
  228. const black = 1 + iota
  229. type node struct {
  230. item Item
  231. parent, left, right *node
  232. color int // black or red
  233. }
  234. var negativeLimitNode *node
  235. //
  236. // Internal node attribute accessors
  237. //
  238. func getColor(n *node) int {
  239. if n == nil {
  240. return black
  241. }
  242. return n.color
  243. }
  244. func (n *node) isLeftChild() bool {
  245. return n == n.parent.left
  246. }
  247. func (n *node) isRightChild() bool {
  248. return n == n.parent.right
  249. }
  250. func (n *node) sibling() *node {
  251. doAssert(n.parent != nil)
  252. if n.isLeftChild() {
  253. return n.parent.right
  254. }
  255. return n.parent.left
  256. }
  257. // Return the minimum node that's larger than N. Return nil if no such
  258. // node is found.
  259. func (n *node) doNext() *node {
  260. if n.right != nil {
  261. m := n.right
  262. for m.left != nil {
  263. m = m.left
  264. }
  265. return m
  266. }
  267. for n != nil {
  268. p := n.parent
  269. if p == nil {
  270. return nil
  271. }
  272. if n.isLeftChild() {
  273. return p
  274. }
  275. n = p
  276. }
  277. return nil
  278. }
  279. // Return the maximum node that's smaller than N. Return nil if no
  280. // such node is found.
  281. func (n *node) doPrev() *node {
  282. if n.left != nil {
  283. return maxPredecessor(n)
  284. }
  285. for n != nil {
  286. p := n.parent
  287. if p == nil {
  288. break
  289. }
  290. if n.isRightChild() {
  291. return p
  292. }
  293. n = p
  294. }
  295. return negativeLimitNode
  296. }
  297. // Return the predecessor of "n".
  298. func maxPredecessor(n *node) *node {
  299. doAssert(n.left != nil)
  300. m := n.left
  301. for m.right != nil {
  302. m = m.right
  303. }
  304. return m
  305. }
  306. //
  307. // Tree methods
  308. //
  309. //
  310. // Private methods
  311. //
  312. func (root *RBTree) recomputeMinNode() {
  313. root.minNode = root.root
  314. if root.minNode != nil {
  315. for root.minNode.left != nil {
  316. root.minNode = root.minNode.left
  317. }
  318. }
  319. }
  320. func (root *RBTree) recomputeMaxNode() {
  321. root.maxNode = root.root
  322. if root.maxNode != nil {
  323. for root.maxNode.right != nil {
  324. root.maxNode = root.maxNode.right
  325. }
  326. }
  327. }
  328. func (root *RBTree) maybeSetMinNode(n *node) {
  329. if root.minNode == nil {
  330. root.minNode = n
  331. root.maxNode = n
  332. } else if n.item.Key < root.minNode.item.Key {
  333. root.minNode = n
  334. }
  335. }
  336. func (root *RBTree) maybeSetMaxNode(n *node) {
  337. if root.maxNode == nil {
  338. root.minNode = n
  339. root.maxNode = n
  340. } else if n.item.Key > root.maxNode.item.Key {
  341. root.maxNode = n
  342. }
  343. }
  344. // Try inserting "item" into the tree. Return nil if the item is
  345. // already in the tree. Otherwise return a new (leaf) node.
  346. func (root *RBTree) doInsert(item Item) *node {
  347. if root.root == nil {
  348. n := &node{item: item}
  349. root.root = n
  350. root.minNode = n
  351. root.maxNode = n
  352. root.count++
  353. return n
  354. }
  355. parent := root.root
  356. for true {
  357. comp := item.Key - parent.item.Key
  358. if comp == 0 {
  359. return nil
  360. } else if comp < 0 {
  361. if parent.left == nil {
  362. n := &node{item: item, parent: parent}
  363. parent.left = n
  364. root.count++
  365. root.maybeSetMinNode(n)
  366. return n
  367. }
  368. parent = parent.left
  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. }
  377. parent = parent.right
  378. }
  379. }
  380. panic("should not reach here")
  381. }
  382. // Find a node whose item >= Key. The 2nd return Value is true iff the
  383. // node.item==Key. Returns (nil, false) if all nodes in the tree are <
  384. // Key.
  385. func (root *RBTree) findGE(key int) (*node, bool) {
  386. n := root.root
  387. for true {
  388. if n == nil {
  389. return nil, false
  390. }
  391. comp := key - n.item.Key
  392. if comp == 0 {
  393. return n, true
  394. } else if comp < 0 {
  395. if n.left != nil {
  396. n = n.left
  397. } else {
  398. return n, false
  399. }
  400. } else {
  401. if n.right != nil {
  402. n = n.right
  403. } else {
  404. succ := n.doNext()
  405. if succ == nil {
  406. return nil, false
  407. }
  408. return succ, key == succ.item.Key
  409. }
  410. }
  411. }
  412. panic("should not reach here")
  413. }
  414. // Delete N from the tree.
  415. func (root *RBTree) doDelete(n *node) {
  416. if n.left != nil && n.right != nil {
  417. pred := maxPredecessor(n)
  418. root.swapNodes(n, pred)
  419. }
  420. doAssert(n.left == nil || n.right == nil)
  421. child := n.right
  422. if child == nil {
  423. child = n.left
  424. }
  425. if n.color == black {
  426. n.color = getColor(child)
  427. root.deleteCase1(n)
  428. }
  429. root.replaceNode(n, child)
  430. if n.parent == nil && child != nil {
  431. child.color = black
  432. }
  433. root.count--
  434. if root.count == 0 {
  435. root.minNode = nil
  436. root.maxNode = nil
  437. } else {
  438. if root.minNode == n {
  439. root.recomputeMinNode()
  440. }
  441. if root.maxNode == n {
  442. root.recomputeMaxNode()
  443. }
  444. }
  445. }
  446. // Move n to the pred's place, and vice versa
  447. //
  448. func (root *RBTree) swapNodes(n, pred *node) {
  449. doAssert(pred != n)
  450. isLeft := pred.isLeftChild()
  451. tmp := *pred
  452. root.replaceNode(n, pred)
  453. pred.color = n.color
  454. if tmp.parent == n {
  455. // swap the positions of n and pred
  456. if isLeft {
  457. pred.left = n
  458. pred.right = n.right
  459. if pred.right != nil {
  460. pred.right.parent = pred
  461. }
  462. } else {
  463. pred.left = n.left
  464. if pred.left != nil {
  465. pred.left.parent = pred
  466. }
  467. pred.right = n
  468. }
  469. n.item = tmp.item
  470. n.parent = pred
  471. n.left = tmp.left
  472. if n.left != nil {
  473. n.left.parent = n
  474. }
  475. n.right = tmp.right
  476. if n.right != nil {
  477. n.right.parent = n
  478. }
  479. } else {
  480. pred.left = n.left
  481. if pred.left != nil {
  482. pred.left.parent = pred
  483. }
  484. pred.right = n.right
  485. if pred.right != nil {
  486. pred.right.parent = pred
  487. }
  488. if isLeft {
  489. tmp.parent.left = n
  490. } else {
  491. tmp.parent.right = n
  492. }
  493. n.item = tmp.item
  494. n.parent = tmp.parent
  495. n.left = tmp.left
  496. if n.left != nil {
  497. n.left.parent = n
  498. }
  499. n.right = tmp.right
  500. if n.right != nil {
  501. n.right.parent = n
  502. }
  503. }
  504. n.color = tmp.color
  505. }
  506. func (root *RBTree) deleteCase1(n *node) {
  507. for true {
  508. if n.parent != nil {
  509. if getColor(n.sibling()) == red {
  510. n.parent.color = red
  511. n.sibling().color = black
  512. if n == n.parent.left {
  513. root.rotateLeft(n.parent)
  514. } else {
  515. root.rotateRight(n.parent)
  516. }
  517. }
  518. if getColor(n.parent) == black &&
  519. getColor(n.sibling()) == black &&
  520. getColor(n.sibling().left) == black &&
  521. getColor(n.sibling().right) == black {
  522. n.sibling().color = red
  523. n = n.parent
  524. continue
  525. } else {
  526. // case 4
  527. if getColor(n.parent) == red &&
  528. getColor(n.sibling()) == black &&
  529. getColor(n.sibling().left) == black &&
  530. getColor(n.sibling().right) == black {
  531. n.sibling().color = red
  532. n.parent.color = black
  533. } else {
  534. root.deleteCase5(n)
  535. }
  536. }
  537. }
  538. break
  539. }
  540. }
  541. func (root *RBTree) deleteCase5(n *node) {
  542. if n == n.parent.left &&
  543. getColor(n.sibling()) == black &&
  544. getColor(n.sibling().left) == red &&
  545. getColor(n.sibling().right) == black {
  546. n.sibling().color = red
  547. n.sibling().left.color = black
  548. root.rotateRight(n.sibling())
  549. } else if n == n.parent.right &&
  550. getColor(n.sibling()) == black &&
  551. getColor(n.sibling().right) == red &&
  552. getColor(n.sibling().left) == black {
  553. n.sibling().color = red
  554. n.sibling().right.color = black
  555. root.rotateLeft(n.sibling())
  556. }
  557. // case 6
  558. n.sibling().color = getColor(n.parent)
  559. n.parent.color = black
  560. if n == n.parent.left {
  561. doAssert(getColor(n.sibling().right) == red)
  562. n.sibling().right.color = black
  563. root.rotateLeft(n.parent)
  564. } else {
  565. doAssert(getColor(n.sibling().left) == red)
  566. n.sibling().left.color = black
  567. root.rotateRight(n.parent)
  568. }
  569. }
  570. func (root *RBTree) replaceNode(oldn, newn *node) {
  571. if oldn.parent == nil {
  572. root.root = newn
  573. } else {
  574. if oldn == oldn.parent.left {
  575. oldn.parent.left = newn
  576. } else {
  577. oldn.parent.right = newn
  578. }
  579. }
  580. if newn != nil {
  581. newn.parent = oldn.parent
  582. }
  583. }
  584. /*
  585. X Y
  586. A Y => X C
  587. B C A B
  588. */
  589. func (root *RBTree) rotateLeft(x *node) {
  590. y := x.right
  591. x.right = y.left
  592. if y.left != nil {
  593. y.left.parent = x
  594. }
  595. y.parent = x.parent
  596. if x.parent == nil {
  597. root.root = y
  598. } else {
  599. if x.isLeftChild() {
  600. x.parent.left = y
  601. } else {
  602. x.parent.right = y
  603. }
  604. }
  605. y.left = x
  606. x.parent = y
  607. }
  608. /*
  609. Y X
  610. X C => A Y
  611. A B B C
  612. */
  613. func (root *RBTree) rotateRight(y *node) {
  614. x := y.left
  615. // Move "B"
  616. y.left = x.right
  617. if x.right != nil {
  618. x.right.parent = y
  619. }
  620. x.parent = y.parent
  621. if y.parent == nil {
  622. root.root = x
  623. } else {
  624. if y.isLeftChild() {
  625. y.parent.left = x
  626. } else {
  627. y.parent.right = x
  628. }
  629. }
  630. x.right = y
  631. y.parent = x
  632. }
  633. func init() {
  634. negativeLimitNode = &node{}
  635. }