rbtree.go 15 KB

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