iterator.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package llrb
  2. type ItemIterator func(i Item) bool
  3. //func (t *Tree) Ascend(iterator ItemIterator) {
  4. // t.AscendGreaterOrEqual(Inf(-1), iterator)
  5. //}
  6. func (t *LLRB) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator) {
  7. t.ascendRange(t.root, greaterOrEqual, lessThan, iterator)
  8. }
  9. func (t *LLRB) ascendRange(h *Node, inf, sup Item, iterator ItemIterator) bool {
  10. if h == nil {
  11. return true
  12. }
  13. if !less(h.Item, sup) {
  14. return t.ascendRange(h.Left, inf, sup, iterator)
  15. }
  16. if less(h.Item, inf) {
  17. return t.ascendRange(h.Right, inf, sup, iterator)
  18. }
  19. if !t.ascendRange(h.Left, inf, sup, iterator) {
  20. return false
  21. }
  22. if !iterator(h.Item) {
  23. return false
  24. }
  25. return t.ascendRange(h.Right, inf, sup, iterator)
  26. }
  27. // AscendGreaterOrEqual will call iterator once for each element greater or equal to
  28. // pivot in ascending order. It will stop whenever the iterator returns false.
  29. func (t *LLRB) AscendGreaterOrEqual(pivot Item, iterator ItemIterator) {
  30. t.ascendGreaterOrEqual(t.root, pivot, iterator)
  31. }
  32. func (t *LLRB) ascendGreaterOrEqual(h *Node, pivot Item, iterator ItemIterator) bool {
  33. if h == nil {
  34. return true
  35. }
  36. if !less(h.Item, pivot) {
  37. if !t.ascendGreaterOrEqual(h.Left, pivot, iterator) {
  38. return false
  39. }
  40. if !iterator(h.Item) {
  41. return false
  42. }
  43. }
  44. return t.ascendGreaterOrEqual(h.Right, pivot, iterator)
  45. }
  46. func (t *LLRB) AscendLessThan(pivot Item, iterator ItemIterator) {
  47. t.ascendLessThan(t.root, pivot, iterator)
  48. }
  49. func (t *LLRB) ascendLessThan(h *Node, pivot Item, iterator ItemIterator) bool {
  50. if h == nil {
  51. return true
  52. }
  53. if !t.ascendLessThan(h.Left, pivot, iterator) {
  54. return false
  55. }
  56. if !iterator(h.Item) {
  57. return false
  58. }
  59. if less(h.Item, pivot) {
  60. return t.ascendLessThan(h.Left, pivot, iterator)
  61. }
  62. return true
  63. }
  64. // DescendLessOrEqual will call iterator once for each element less than the
  65. // pivot in descending order. It will stop whenever the iterator returns false.
  66. func (t *LLRB) DescendLessOrEqual(pivot Item, iterator ItemIterator) {
  67. t.descendLessOrEqual(t.root, pivot, iterator)
  68. }
  69. func (t *LLRB) descendLessOrEqual(h *Node, pivot Item, iterator ItemIterator) bool {
  70. if h == nil {
  71. return true
  72. }
  73. if less(h.Item, pivot) || !less(pivot, h.Item) {
  74. if !t.descendLessOrEqual(h.Right, pivot, iterator) {
  75. return false
  76. }
  77. if !iterator(h.Item) {
  78. return false
  79. }
  80. }
  81. return t.descendLessOrEqual(h.Left, pivot, iterator)
  82. }