rbtree.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. return &iter.node.item
  231. }
  232. // Next creates a new iterator that points to the successor of the current element.
  233. //
  234. // REQUIRES: !iter.Limit()
  235. func (iter Iterator) Next() Iterator {
  236. doAssert(!iter.Limit())
  237. if iter.NegativeLimit() {
  238. return Iterator{iter.tree, iter.tree.minNode}
  239. }
  240. return Iterator{iter.tree, iter.node.doNext()}
  241. }
  242. // Prev creates a new iterator that points to the predecessor of the current
  243. // node.
  244. //
  245. // REQUIRES: !iter.NegativeLimit()
  246. func (iter Iterator) Prev() Iterator {
  247. doAssert(!iter.NegativeLimit())
  248. if !iter.Limit() {
  249. return Iterator{iter.tree, iter.node.doPrev()}
  250. }
  251. if iter.tree.maxNode == nil {
  252. return Iterator{iter.tree, negativeLimitNode}
  253. }
  254. return Iterator{iter.tree, iter.tree.maxNode}
  255. }
  256. func doAssert(b bool) {
  257. if !b {
  258. panic("rbtree internal assertion failed")
  259. }
  260. }
  261. const red = iota
  262. const black = 1 + iota
  263. type node struct {
  264. item Item
  265. parent, left, right *node
  266. color int // black or red
  267. }
  268. var negativeLimitNode *node
  269. //
  270. // Internal node attribute accessors
  271. //
  272. func getColor(n *node) int {
  273. if n == nil {
  274. return black
  275. }
  276. return n.color
  277. }
  278. func (n *node) isLeftChild() bool {
  279. return n == n.parent.left
  280. }
  281. func (n *node) isRightChild() bool {
  282. return n == n.parent.right
  283. }
  284. func (n *node) sibling() *node {
  285. doAssert(n.parent != nil)
  286. if n.isLeftChild() {
  287. return n.parent.right
  288. }
  289. return n.parent.left
  290. }
  291. // Return the minimum node that's larger than N. Return nil if no such
  292. // node is found.
  293. func (n *node) doNext() *node {
  294. if n.right != nil {
  295. m := n.right
  296. for m.left != nil {
  297. m = m.left
  298. }
  299. return m
  300. }
  301. for n != nil {
  302. p := n.parent
  303. if p == nil {
  304. return nil
  305. }
  306. if n.isLeftChild() {
  307. return p
  308. }
  309. n = p
  310. }
  311. return nil
  312. }
  313. // Return the maximum node that's smaller than N. Return nil if no
  314. // such node is found.
  315. func (n *node) doPrev() *node {
  316. if n.left != nil {
  317. return maxPredecessor(n)
  318. }
  319. for n != nil {
  320. p := n.parent
  321. if p == nil {
  322. break
  323. }
  324. if n.isRightChild() {
  325. return p
  326. }
  327. n = p
  328. }
  329. return negativeLimitNode
  330. }
  331. // Return the predecessor of "n".
  332. func maxPredecessor(n *node) *node {
  333. doAssert(n.left != nil)
  334. m := n.left
  335. for m.right != nil {
  336. m = m.right
  337. }
  338. return m
  339. }
  340. //
  341. // Tree methods
  342. //
  343. //
  344. // Private methods
  345. //
  346. func (tree *RBTree) recomputeMinNode() {
  347. tree.minNode = tree.root
  348. if tree.minNode != nil {
  349. for tree.minNode.left != nil {
  350. tree.minNode = tree.minNode.left
  351. }
  352. }
  353. }
  354. func (tree *RBTree) recomputeMaxNode() {
  355. tree.maxNode = tree.root
  356. if tree.maxNode != nil {
  357. for tree.maxNode.right != nil {
  358. tree.maxNode = tree.maxNode.right
  359. }
  360. }
  361. }
  362. func (tree *RBTree) maybeSetMinNode(n *node) {
  363. if tree.minNode == nil {
  364. tree.minNode = n
  365. tree.maxNode = n
  366. } else if n.item.Key < tree.minNode.item.Key {
  367. tree.minNode = n
  368. }
  369. }
  370. func (tree *RBTree) maybeSetMaxNode(n *node) {
  371. if tree.maxNode == nil {
  372. tree.minNode = n
  373. tree.maxNode = n
  374. } else if n.item.Key > tree.maxNode.item.Key {
  375. tree.maxNode = n
  376. }
  377. }
  378. // Try inserting "item" into the tree. Return nil if the item is
  379. // already in the tree. Otherwise return a new (leaf) node.
  380. func (tree *RBTree) doInsert(item Item) *node {
  381. if tree.root == nil {
  382. n := &node{item: item}
  383. tree.root = n
  384. tree.minNode = n
  385. tree.maxNode = n
  386. tree.count++
  387. return n
  388. }
  389. parent := tree.root
  390. for true {
  391. comp := item.Key - parent.item.Key
  392. if comp == 0 {
  393. return nil
  394. } else if comp < 0 {
  395. if parent.left == nil {
  396. n := &node{item: item, parent: parent}
  397. parent.left = n
  398. tree.count++
  399. tree.maybeSetMinNode(n)
  400. return n
  401. }
  402. parent = parent.left
  403. } else {
  404. if parent.right == nil {
  405. n := &node{item: item, parent: parent}
  406. parent.right = n
  407. tree.count++
  408. tree.maybeSetMaxNode(n)
  409. return n
  410. }
  411. parent = parent.right
  412. }
  413. }
  414. panic("should not reach here")
  415. }
  416. // Find a node whose item >= Key. The 2nd return Value is true iff the
  417. // node.item==Key. Returns (nil, false) if all nodes in the tree are <
  418. // Key.
  419. func (tree *RBTree) findGE(key int) (*node, bool) {
  420. n := tree.root
  421. for true {
  422. if n == nil {
  423. return nil, false
  424. }
  425. comp := key - n.item.Key
  426. if comp == 0 {
  427. return n, true
  428. } else if comp < 0 {
  429. if n.left != nil {
  430. n = n.left
  431. } else {
  432. return n, false
  433. }
  434. } else {
  435. if n.right != nil {
  436. n = n.right
  437. } else {
  438. succ := n.doNext()
  439. if succ == nil {
  440. return nil, false
  441. }
  442. return succ, key == succ.item.Key
  443. }
  444. }
  445. }
  446. panic("should not reach here")
  447. }
  448. // Delete N from the tree.
  449. func (tree *RBTree) doDelete(n *node) {
  450. if n.left != nil && n.right != nil {
  451. pred := maxPredecessor(n)
  452. tree.swapNodes(n, pred)
  453. }
  454. doAssert(n.left == nil || n.right == nil)
  455. child := n.right
  456. if child == nil {
  457. child = n.left
  458. }
  459. if n.color == black {
  460. n.color = getColor(child)
  461. tree.deleteCase1(n)
  462. }
  463. tree.replaceNode(n, child)
  464. if n.parent == nil && child != nil {
  465. child.color = black
  466. }
  467. tree.count--
  468. if tree.count == 0 {
  469. tree.minNode = nil
  470. tree.maxNode = nil
  471. } else {
  472. if tree.minNode == n {
  473. tree.recomputeMinNode()
  474. }
  475. if tree.maxNode == n {
  476. tree.recomputeMaxNode()
  477. }
  478. }
  479. }
  480. // Move n to the pred's place, and vice versa
  481. //
  482. func (tree *RBTree) swapNodes(n, pred *node) {
  483. doAssert(pred != n)
  484. isLeft := pred.isLeftChild()
  485. tmp := *pred
  486. tree.replaceNode(n, pred)
  487. pred.color = n.color
  488. if tmp.parent == n {
  489. // swap the positions of n and pred
  490. if isLeft {
  491. pred.left = n
  492. pred.right = n.right
  493. if pred.right != nil {
  494. pred.right.parent = pred
  495. }
  496. } else {
  497. pred.left = n.left
  498. if pred.left != nil {
  499. pred.left.parent = pred
  500. }
  501. pred.right = n
  502. }
  503. n.item = tmp.item
  504. n.parent = pred
  505. n.left = tmp.left
  506. if n.left != nil {
  507. n.left.parent = n
  508. }
  509. n.right = tmp.right
  510. if n.right != nil {
  511. n.right.parent = n
  512. }
  513. } else {
  514. pred.left = n.left
  515. if pred.left != nil {
  516. pred.left.parent = pred
  517. }
  518. pred.right = n.right
  519. if pred.right != nil {
  520. pred.right.parent = pred
  521. }
  522. if isLeft {
  523. tmp.parent.left = n
  524. } else {
  525. tmp.parent.right = n
  526. }
  527. n.item = tmp.item
  528. n.parent = tmp.parent
  529. n.left = tmp.left
  530. if n.left != nil {
  531. n.left.parent = n
  532. }
  533. n.right = tmp.right
  534. if n.right != nil {
  535. n.right.parent = n
  536. }
  537. }
  538. n.color = tmp.color
  539. }
  540. func (tree *RBTree) deleteCase1(n *node) {
  541. for true {
  542. if n.parent != nil {
  543. if getColor(n.sibling()) == red {
  544. n.parent.color = red
  545. n.sibling().color = black
  546. if n == n.parent.left {
  547. tree.rotateLeft(n.parent)
  548. } else {
  549. tree.rotateRight(n.parent)
  550. }
  551. }
  552. if getColor(n.parent) == black &&
  553. getColor(n.sibling()) == black &&
  554. getColor(n.sibling().left) == black &&
  555. getColor(n.sibling().right) == black {
  556. n.sibling().color = red
  557. n = n.parent
  558. continue
  559. } else {
  560. // case 4
  561. if getColor(n.parent) == red &&
  562. getColor(n.sibling()) == black &&
  563. getColor(n.sibling().left) == black &&
  564. getColor(n.sibling().right) == black {
  565. n.sibling().color = red
  566. n.parent.color = black
  567. } else {
  568. tree.deleteCase5(n)
  569. }
  570. }
  571. }
  572. break
  573. }
  574. }
  575. func (tree *RBTree) deleteCase5(n *node) {
  576. if n == n.parent.left &&
  577. getColor(n.sibling()) == black &&
  578. getColor(n.sibling().left) == red &&
  579. getColor(n.sibling().right) == black {
  580. n.sibling().color = red
  581. n.sibling().left.color = black
  582. tree.rotateRight(n.sibling())
  583. } else if n == n.parent.right &&
  584. getColor(n.sibling()) == black &&
  585. getColor(n.sibling().right) == red &&
  586. getColor(n.sibling().left) == black {
  587. n.sibling().color = red
  588. n.sibling().right.color = black
  589. tree.rotateLeft(n.sibling())
  590. }
  591. // case 6
  592. n.sibling().color = getColor(n.parent)
  593. n.parent.color = black
  594. if n == n.parent.left {
  595. doAssert(getColor(n.sibling().right) == red)
  596. n.sibling().right.color = black
  597. tree.rotateLeft(n.parent)
  598. } else {
  599. doAssert(getColor(n.sibling().left) == red)
  600. n.sibling().left.color = black
  601. tree.rotateRight(n.parent)
  602. }
  603. }
  604. func (tree *RBTree) replaceNode(oldn, newn *node) {
  605. if oldn.parent == nil {
  606. tree.root = newn
  607. } else {
  608. if oldn == oldn.parent.left {
  609. oldn.parent.left = newn
  610. } else {
  611. oldn.parent.right = newn
  612. }
  613. }
  614. if newn != nil {
  615. newn.parent = oldn.parent
  616. }
  617. }
  618. /*
  619. X Y
  620. A Y => X C
  621. B C A B
  622. */
  623. func (tree *RBTree) rotateLeft(x *node) {
  624. y := x.right
  625. x.right = y.left
  626. if y.left != nil {
  627. y.left.parent = x
  628. }
  629. y.parent = x.parent
  630. if x.parent == nil {
  631. tree.root = y
  632. } else {
  633. if x.isLeftChild() {
  634. x.parent.left = y
  635. } else {
  636. x.parent.right = y
  637. }
  638. }
  639. y.left = x
  640. x.parent = y
  641. }
  642. /*
  643. Y X
  644. X C => A Y
  645. A B B C
  646. */
  647. func (tree *RBTree) rotateRight(y *node) {
  648. x := y.left
  649. // Move "B"
  650. y.left = x.right
  651. if x.right != nil {
  652. x.right.parent = y
  653. }
  654. x.parent = y.parent
  655. if y.parent == nil {
  656. tree.root = x
  657. } else {
  658. if y.isLeftChild() {
  659. y.parent.left = x
  660. } else {
  661. y.parent.right = x
  662. }
  663. }
  664. x.right = y
  665. y.parent = x
  666. }
  667. func init() {
  668. negativeLimitNode = &node{}
  669. }