File: interval_tree.h

package info (click to toggle)
libset-intervaltree-perl 0.12-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 364 kB
  • sloc: cpp: 686; perl: 60; makefile: 3
file content (1043 lines) | stat: -rw-r--r-- 32,649 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
#ifndef INTERVALTREE_H_
#define INTERVALTREE_H_

#include <cmath>
#include <cstdlib>
#include <cassert>
#include <limits>
#include <algorithm>
#include <sstream>
#include <vector>
#include <string>

//  The interval_tree.h file contains code for 
//  interval trees implemented using red-black-trees as described in 
//  the book _Introduction_To_Algorithms_ by Cormen, Leisserson, 
//  and Rivest.  

// The low should return the lowest point of the interval and
// the high should return the highest point of the interval.  

template<typename T, typename N=long>
class IntervalTree {
public:
  enum color_t {BLACK, RED};

  class Node {
    friend class IntervalTree<T,N>;
  public:
    std::string str(Node *, Node *) const;
    Node();
    Node(const T&, N, N);
    virtual ~Node();
    N low() const;
    N high() const;
    T value() const;
  protected:
    T value_;
    N key;
    N high_;
    N maxHigh;
    color_t color;
    Node * left;
    Node * right;
    Node * parent;
  };

  IntervalTree();
  ~IntervalTree();
  std::string str() const;
  void remove(N, N, std::vector<T>&);
  template <class F> void remove(N, N, const F&, std::vector<T>&);
  void remove_window(N, N, std::vector<T>&);
  template <class F> void remove_window(N, N, const F&, std::vector<T>&);
  Node * insert(const T&, N, N);
  void fetch(N, N, std::vector<T>&);
  void fetch_window(N, N, std::vector<T>&);
  T fetch_nearest_up(typename IntervalTree<T,N>::Node* x, N value);
  T fetch_nearest_up(N value);
  typename IntervalTree<T,N>::Node* fetch_nearest_down(typename IntervalTree<T,N>::Node* x, N value);
  T fetch_nearest_down(N value);
protected:
  void fetch_node(N, N, std::vector<Node*>&);
  void fetch_window_node(N, N, std::vector<Node*>&);
  T remove(Node *);
  Node * GetPredecessorOf(Node *) const;
  Node * GetSuccessorOf(Node *) const;
  void check() const;

  /*  A sentinel is used for root and for nil.  These sentinels are */
  /*  created when ITTreeCreate is caled.  root->left should always */
  /*  point to the node which is the root of the tree.  nil points to a */
  /*  node which should always be black but has aribtrary children and */
  /*  parent and no key or info.  The point of using these sentinels is so */
  /*  that the root and nil nodes do not require special cases in the code */
  Node * root;
  Node * nil;

  N Overlap(N a1, N a2, N b1, N b2);
  N Contain(N a1, N a2, N b1, N b2);
  void LeftRotate(Node *);
  void RightRotate(Node *);
  void TreeInsertHelp(Node *);
  void TreePrintHelper(Node *, std::stringstream&) const;
  void FixUpMaxHigh(Node *);
  void DeleteFixUp(Node *);
  void CheckMaxHighFields(Node *) const;
  bool CheckMaxHighFieldsHelper(Node * y, 
      const N currentHigh,
      bool match) const;
};

// If the symbol CHECK_INTERVAL_TREE_ASSUMPTIONS is defined then the
// code does a lot of extra checking to make sure certain assumptions
// are satisfied.  This only needs to be done if you suspect bugs are
// present or if you make significant changes and want to make sure
// your changes didn't mess anything up.
// #define CHECK_INTERVAL_TREE_ASSUMPTIONS 1

template<typename T, typename N> IntervalTree<T,N>::Node::Node() {
}

template<typename T, typename N>
IntervalTree<T,N>::Node::Node(const T& value__, N lowPoint, N highPoint) 
  : value_ (value__),
    key(lowPoint), 
    high_(highPoint), 
    maxHigh(highPoint) 
{
}

template<typename T, typename N>
IntervalTree<T,N>::Node::~Node()
{
}

template<typename T, typename N>
IntervalTree<T,N>::IntervalTree()
{
  nil = new typename IntervalTree<T,N>::Node();
  nil->left = nil->right = nil->parent = nil;
  nil->color = BLACK;
  nil->key = nil->high_ = nil->maxHigh = std::numeric_limits<N>::min();
  
  root = new typename IntervalTree<T,N>::Node();
  root->parent = root->left = root->right = nil;
  root->key = root->high_ = root->maxHigh = std::numeric_limits<N>::max();
  root->color=BLACK;
}

template<typename T, typename N>
N IntervalTree<T,N>::Node::low() const {
  return key;
}

template<typename T, typename N>
N IntervalTree<T,N>::Node::high() const {
  return high_;
}

template<typename T, typename N>
T IntervalTree<T,N>::Node::value() const {
  return value_;
}

/***********************************************************************/
/*  FUNCTION:  LeftRotate */
/**/
/*  INPUTS:  the node to rotate on */
/**/
/*  OUTPUT:  None */
/**/
/*  Modifies Input: this, x */
/**/
/*  EFFECTS:  Rotates as described in _Introduction_To_Algorithms by */
/*            Cormen, Leiserson, Rivest (Chapter 14).  Basically this */
/*            makes the parent of x be to the left of x, x the parent of */
/*            its parent before the rotation and fixes other pointers */
/*            accordingly. Also updates the maxHigh fields of x and y */
/*            after rotation. */
/***********************************************************************/

template<typename T, typename N>
void IntervalTree<T,N>::LeftRotate(typename IntervalTree<T,N>::Node* x) {
  typename IntervalTree<T,N>::Node* y;
 
  /*  I originally wrote this function to use the sentinel for */
  /*  nil to avoid checking for nil.  However this introduces a */
  /*  very subtle bug because sometimes this function modifies */
  /*  the parent pointer of nil.  This can be a problem if a */
  /*  function which calls LeftRotate also uses the nil sentinel */
  /*  and expects the nil sentinel's parent pointer to be unchanged */
  /*  after calling this function.  For example, when DeleteFixUP */
  /*  calls LeftRotate it expects the parent pointer of nil to be */
  /*  unchanged. */

  y=x->right;
  x->right=y->left;

  if (y->left != nil) y->left->parent=x; /* used to use sentinel here */
  /* and do an unconditional assignment instead of testing for nil */
  
  y->parent=x->parent;   

  /* instead of checking if x->parent is the root as in the book, we */
  /* count on the root sentinel to implicitly take care of this case */
  if( x == x->parent->left) {
    x->parent->left=y;
  } else {
    x->parent->right=y;
  }
  y->left=x;
  x->parent=y;

  x->maxHigh=std::max(x->left->maxHigh,std::max(x->right->maxHigh,x->high_));
  y->maxHigh=std::max(x->maxHigh,std::max(y->right->maxHigh,y->high_));
#ifdef CHECK_INTERVAL_TREE_ASSUMPTIONS
  check();
#elif defined(DEBUG_ASSERT)
  assert(nil->color != RED || !"nil not red in ITLeftRotate");
  assert((nil->maxHigh!=std::numeric_limits<N>::min())
         || !"nil->maxHigh != std::numeric_limits<N>::min() in ITLeftRotate");
#endif
}


/***********************************************************************/
/*  FUNCTION:  RighttRotate */
/**/
/*  INPUTS:  node to rotate on */
/**/
/*  OUTPUT:  None */
/**/
/*  Modifies Input?: this, y */
/**/
/*  EFFECTS:  Rotates as described in _Introduction_To_Algorithms by */
/*            Cormen, Leiserson, Rivest (Chapter 14).  Basically this */
/*            makes the parent of x be to the left of x, x the parent of */
/*            its parent before the rotation and fixes other pointers */
/*            accordingly. Also updates the maxHigh fields of x and y */
/*            after rotation. */
/***********************************************************************/


template<typename T, typename N>
void IntervalTree<T,N>::RightRotate(typename IntervalTree<T,N>::Node* y) {
  typename IntervalTree<T,N>::Node* x;

  /*  I originally wrote this function to use the sentinel for */
  /*  nil to avoid checking for nil.  However this introduces a */
  /*  very subtle bug because sometimes this function modifies */
  /*  the parent pointer of nil.  This can be a problem if a */
  /*  function which calls LeftRotate also uses the nil sentinel */
  /*  and expects the nil sentinel's parent pointer to be unchanged */
  /*  after calling this function.  For example, when DeleteFixUP */
  /*  calls LeftRotate it expects the parent pointer of nil to be */
  /*  unchanged. */

  x=y->left;
  y->left=x->right;

  if (nil != x->right)  x->right->parent=y; /*used to use sentinel here */
  /* and do an unconditional assignment instead of testing for nil */

  /* instead of checking if x->parent is the root as in the book, we */
  /* count on the root sentinel to implicitly take care of this case */
  x->parent=y->parent;
  if( y == y->parent->left) {
    y->parent->left=x;
  } else {
    y->parent->right=x;
  }
  x->right=y;
  y->parent=x;

  y->maxHigh=std::max(y->left->maxHigh,std::max(y->right->maxHigh,y->high_));
  x->maxHigh=std::max(x->left->maxHigh,std::max(y->maxHigh,x->high_));
#ifdef CHECK_INTERVAL_TREE_ASSUMPTIONS
  check();
#elif defined(DEBUG_ASSERT)
  assert(nil->color != RED || !"nil not red in ITRightRotate");
  assert((nil->maxHigh!=std::numeric_limits<N>::min())
        || !"nil->maxHigh != std::numeric_limits<N>::min() in ITRightRotate");
#endif
}

/***********************************************************************/
/*  FUNCTION:  TreeInsertHelp  */
/**/
/*  INPUTS:  z is the node to insert */
/**/
/*  OUTPUT:  none */
/**/
/*  Modifies Input:  this, z */
/**/
/*  EFFECTS:  Inserts z into the tree as if it were a regular binary tree */
/*            using the algorithm described in _Introduction_To_Algorithms_ */
/*            by Cormen et al.  This funciton is only intended to be called */
/*            by the InsertTree function and not by the user */
/***********************************************************************/

template<typename T, typename N>
void IntervalTree<T,N>::TreeInsertHelp(typename IntervalTree<T,N>::Node* z) {
  /*  This function should only be called by InsertITTree (see above) */
  typename IntervalTree<T,N>::Node* x;
  typename IntervalTree<T,N>::Node* y;
    
  z->left=z->right=nil;
  y=root;
  x=root->left;
  while( x != nil) {
    y=x;
    if ( x->key > z->key) { 
      x=x->left;
    } else { /* x->key <= z->key */
      x=x->right;
    }
  }
  z->parent=y;
  if ( (y == root) ||
       (y->key > z->key) ) { 
    y->left=z;
  } else {
    y->right=z;
  }


#if defined(DEBUG_ASSERT)
  assert(nil->color != RED || !"nil not red in ITTreeInsertHelp");
  assert((nil->maxHigh!=std::numeric_limits<N>::min())
        || !"nil->maxHigh != std::numeric_limits<N>::min() in ITTreeInsertHelp");
#endif
}


/***********************************************************************/
/*  FUNCTION:  FixUpMaxHigh  */
/**/
/*  INPUTS:  x is the node to start from*/
/**/
/*  OUTPUT:  none */
/**/
/*  Modifies Input:  this */
/**/
/*  EFFECTS:  Travels up to the root fixing the maxHigh fields after */
/*            an insertion or deletion */
/***********************************************************************/

template<typename T, typename N>
void IntervalTree<T,N>::FixUpMaxHigh(typename IntervalTree<T,N>::Node * x) {
  while(x != root) {
    x->maxHigh=std::max(x->high_,std::max(x->left->maxHigh,x->right->maxHigh));
    x=x->parent;
  }
#ifdef CHECK_INTERVAL_TREE_ASSUMPTIONS
  check();
#endif
}

/*  Before calling InsertNode  the node x should have its key set */

/***********************************************************************/
/*  FUNCTION:  InsertNode */
/**/
/*  INPUTS:  newInterval is the interval to insert*/
/**/
/*  OUTPUT:  This function returns a pointer to the newly inserted node */
/*           which is guarunteed to be valid until this node is deleted. */
/*           What this means is if another data structure stores this */
/*           pointer then the tree does not need to be searched when this */
/*           is to be deleted. */
/**/
/*  Modifies Input: tree */
/**/
/*  EFFECTS:  Creates a node node which contains the appropriate key and */
/*            info pointers and inserts it into the tree. */
/***********************************************************************/

template <typename T, typename N>
typename IntervalTree<T,N>::Node* IntervalTree<T,N>::insert(const T& newInterval, N low, N high)
{
  typename IntervalTree<T,N>::Node * y;
  typename IntervalTree<T,N>::Node * x;
  typename IntervalTree<T,N>::Node * newNode;

  x = new typename IntervalTree<T,N>::Node(newInterval, low, high);
  TreeInsertHelp(x);
  FixUpMaxHigh(x->parent);
  newNode = x;
  x->color=RED;
  while(x->parent->color == RED) { /* use sentinel instead of checking for root */
    if (x->parent == x->parent->parent->left) {
      y=x->parent->parent->right;
      if (y->color == RED) {
        x->parent->color=BLACK;
        y->color=BLACK;
        x->parent->parent->color=RED;
        x=x->parent->parent;
      } else {
        if (x == x->parent->right) {
          x=x->parent;
          LeftRotate(x);
        }
        x->parent->color=BLACK;
        x->parent->parent->color=RED;
        RightRotate(x->parent->parent);
      } 
    } else { /* case for x->parent == x->parent->parent->right */
             /* this part is just like the section above with */
             /* left and right interchanged */
      y=x->parent->parent->left;
      if (y->color == RED) {
        x->parent->color=BLACK;
        y->color=BLACK;
        x->parent->parent->color=RED;
        x=x->parent->parent;
      } else {
        if (x == x->parent->left) {
          x=x->parent;
          RightRotate(x);
        }
        x->parent->color=BLACK;
        x->parent->parent->color=RED;
        LeftRotate(x->parent->parent);
      } 
    }
  }
  root->left->color=BLACK;
  return(newNode);

#ifdef CHECK_INTERVAL_TREE_ASSUMPTIONS
  check();
#elif defined(DEBUG_ASSERT)
  assert(nil->color != RED || !"nil not red in ITTreeInsert");
  assert(root->color != RED || !"root not red in ITTreeInsert");
  assert((nil->maxHigh!=std::numeric_limits<N>::min())
         || !"nil->maxHigh != std::numeric_limits<N>::min() in ITTreeInsert");
#endif
}

/***********************************************************************/
/*  FUNCTION:  GetSuccessorOf  */
/**/
/*    INPUTS:  x is the node we want the succesor of */
/**/
/*    OUTPUT:  This function returns the successor of x or NULL if no */
/*             successor exists. */
/**/
/*    Modifies Input: none */
/**/
/*    Note:  uses the algorithm in _Introduction_To_Algorithms_ */
/***********************************************************************/
  
template<typename T, typename N> 
typename IntervalTree<T,N>::Node * IntervalTree<T,N>::GetSuccessorOf(typename IntervalTree<T,N>::Node * x) const
{ 
  typename IntervalTree<T,N>::Node* y;

  if (nil != (y = x->right)) { /* assignment to y is intentional */
    while(y->left != nil) { /* returns the minium of the right subtree of x */
      y=y->left;
    }
    return(y);
  } else {
    y=x->parent;
    while(x == y->right) { /* sentinel used instead of checking for nil */
      x=y;
      y=y->parent;
    }
    if (y == root) return(nil);
    return(y);
  }
}

/***********************************************************************/
/*  FUNCTION:  GetPredecessorOf  */
/**/
/*    INPUTS:  x is the node to get predecessor of */
/**/
/*    OUTPUT:  This function returns the predecessor of x or NULL if no */
/*             predecessor exists. */
/**/
/*    Modifies Input: none */
/**/
/*    Note:  uses the algorithm in _Introduction_To_Algorithms_ */
/***********************************************************************/

template<typename T, typename N>
typename IntervalTree<T,N>::Node * IntervalTree<T,N>::GetPredecessorOf(typename IntervalTree<T,N>::Node * x) const {
  typename IntervalTree<T,N>::Node* y;

  if (nil != (y = x->left)) { /* assignment to y is intentional */
    while(y->right != nil) { /* returns the maximum of the left subtree of x */
      y=y->right;
    }
    return(y);
  } else {
    y=x->parent;
    while(x == y->left) { 
      if (y == root) return(nil); 
      x=y;
      y=y->parent;
    }
    return(y);
  }
}

/***********************************************************************/
/*  FUNCTION:  str */
/**/
/*    INPUTS:  none */
/**/
/*    OUTPUT:  none  */
/**/
/*    EFFECTS:  This function recursively prints the nodes of the tree */
/*              inorder. */
/**/
/*    Modifies Input: none */
/**/
/*    Note:    This function should only be called from ITTreePrint */
/***********************************************************************/

template<typename T, typename N>
std::string IntervalTree<T,N>::Node::str(typename IntervalTree<T,N>::Node * nil,
                             typename IntervalTree<T,N>::Node * root) const {
  std::stringstream s;

  s << value_;
  s << ", k=" << key << ", h=" << high_ << ", mH=" << maxHigh;
  s << "  l->key=";
  if( left == nil) s << "NULL"; else s << left->key;
  s << "  r->key=";
  if( right == nil) s << "NULL"; else s << right->key;
  s << "  p->key=";
  if( parent == root) s << "NULL"; else s << parent->key;
  s << "  color=" << (color == RED ? "RED" : "BLACK") << std::endl;
  return s.str();
}

template<typename T, typename N>
void IntervalTree<T,N>::TreePrintHelper(typename IntervalTree<T,N>::Node* x, std::stringstream &s) const {
  if (x != nil) {
    TreePrintHelper(x->left, s);
    s << x->str(nil,root);
    TreePrintHelper(x->right, s);
  }
}

template<typename T, typename N>
IntervalTree<T,N>::~IntervalTree() {

  typename IntervalTree<T,N>::Node * x = root->left;
  typename std::vector<typename IntervalTree<T,N>::Node *> stuffToFree;

  if (x != nil) {
    if (x->left != nil) {
      stuffToFree.push_back(x->left);
    }
    if (x->right != nil) {
      stuffToFree.push_back(x->right);
    }
    delete x;
    while( !stuffToFree.empty() ) {
      x = stuffToFree.back();
      stuffToFree.pop_back();
      if (x->left != nil) {
        stuffToFree.push_back(x->left);
      }
      if (x->right != nil) {
        stuffToFree.push_back(x->right);
      }
      delete x;
    }
  }
  delete nil;
  delete root;
}


/***********************************************************************/
/*  FUNCTION:  str */
/**/
/*    INPUTS:  none */
/**/
/*    OUTPUT:  none */
/**/
/*    EFFECT:  This function recursively prints the nodes of the tree */
/*             inorder. */
/**/
/*    Modifies Input: none */
/**/
/***********************************************************************/

template<typename T, typename N>
std::string IntervalTree<T,N>::str() const {
  std::stringstream s;
  TreePrintHelper(root->left, s);
  return s.str();
}

/***********************************************************************/
/*  FUNCTION:  DeleteFixUp */
/**/
/*    INPUTS:  x is the child of the spliced */
/*             out node in remove. */
/**/
/*    OUTPUT:  none */
/**/
/*    EFFECT:  Performs rotations and changes colors to restore red-black */
/*             properties after a node is deleted */
/**/
/*    Modifies Input: this, x */
/**/
/*    The algorithm from this function is from _Introduction_To_Algorithms_ */
/***********************************************************************/

template<typename T,typename N>
void IntervalTree<T,N>::DeleteFixUp(typename IntervalTree<T,N>::Node* x) {
  typename IntervalTree<T,N>::Node * w;
  typename IntervalTree<T,N>::Node * rootLeft = root->left;

  while( (x->color == BLACK) && (rootLeft != x)) {
    if (x == x->parent->left) {
      w=x->parent->right;
      if (w->color == RED) {
        w->color=BLACK;
        x->parent->color=RED;
        LeftRotate(x->parent);
        w=x->parent->right;
      }
      if ( (w->right->color == BLACK) && (w->left->color == BLACK) ) { 
        w->color=RED;
        x=x->parent;
      } else {
        if (w->right->color == BLACK) {
          w->left->color=BLACK;
          w->color=RED;
          RightRotate(w);
          w=x->parent->right;
        }
        w->color=x->parent->color;
        x->parent->color=BLACK;
        w->right->color=BLACK;
        LeftRotate(x->parent);
        x=rootLeft; /* this is to exit while loop */
      }
    } else { /* the code below is has left and right switched from above */
      w=x->parent->left;
      if (w->color == RED) {
        w->color=BLACK;
        x->parent->color=RED;
        RightRotate(x->parent);
        w=x->parent->left;
      }
      if ( (w->right->color == BLACK) && (w->left->color == BLACK) ) { 
        w->color=RED;
        x=x->parent;
      } else {
        if (w->left->color == BLACK) {
          w->right->color=BLACK;
          w->color=RED;
          LeftRotate(w);
          w=x->parent->left;
        }
        w->color=x->parent->color;
        x->parent->color=BLACK;
        w->left->color=BLACK;
        RightRotate(x->parent);
        x=rootLeft; /* this is to exit while loop */
      }
    }
  }
  x->color=BLACK;

#ifdef CHECK_INTERVAL_TREE_ASSUMPTIONS
  check();
#elif defined(DEBUG_ASSERT)
  assert(nil->color != BLACK || !"nil not black in ITDeleteFixUp");
  assert((nil->maxHigh!=std::numeric_limits<N>::min())
         || !"nil->maxHigh != std::numeric_limits<N>::min() in ITDeleteFixUp");
#endif
}


/***********************************************************************/
/*  FUNCTION:  remove */
/**/
/*    INPUTS:  tree is the tree to delete node z from */
/**/
/*    OUTPUT:  returns the Interval stored at deleted node */
/**/
/*    EFFECT:  Deletes z from tree and but don't call destructor */
/*             Then calls FixUpMaxHigh to fix maxHigh fields then calls */
/*             ITDeleteFixUp to restore red-black properties */
/**/
/*    Modifies Input:  z */
/**/
/*    The algorithm from this function is from _Introduction_To_Algorithms_ */
/***********************************************************************/

template<typename T, typename N>
T IntervalTree<T,N>::remove(typename IntervalTree<T,N>::Node * z){
  typename IntervalTree<T,N>::Node* y;
  typename IntervalTree<T,N>::Node* x;
  T returnValue = z->value();

  y= ((z->left == nil) || (z->right == nil)) ? z : GetSuccessorOf(z);
  x= (y->left == nil) ? y->right : y->left;
  if (root == (x->parent = y->parent)) { /* assignment of y->p to x->p is intentional */
    root->left=x;
  } else {
    if (y == y->parent->left) {
      y->parent->left=x;
    } else {
      y->parent->right=x;
    }
  }
  if (y != z) { /* y should not be nil in this case */

#ifdef DEBUG_ASSERT
    assert( (y!=nil) || !"y is nil in remove");
#endif
    /* y is the node to splice out and x is its child */
  
    y->maxHigh = std::numeric_limits<N>::min();
    y->left=z->left;
    y->right=z->right;
    y->parent=z->parent;
    z->left->parent=z->right->parent=y;
    if (z == z->parent->left) {
      z->parent->left=y; 
    } else {
      z->parent->right=y;
    }
    FixUpMaxHigh(x->parent); 
    if (y->color == BLACK) {
      y->color = z->color;
      DeleteFixUp(x);
    } else
      y->color = z->color; 
    delete z;
#ifdef CHECK_INTERVAL_TREE_ASSUMPTIONS
    check();
#elif defined(DEBUG_ASSERT)
    assert(nil->color != BLACK || !"nil not black in ITDelete");
    assert((nil->maxHigh!=std::numeric_limits<N>::min())
        && !"nil->maxHigh != std::numeric_limits<N>::min() in ITDelete");
#endif
  } else {
    FixUpMaxHigh(x->parent);
    if (y->color == BLACK) DeleteFixUp(x);
    delete y;
#ifdef CHECK_INTERVAL_TREE_ASSUMPTIONS
    check();
#elif defined(DEBUG_ASSERT)
    assert(nil->color != BLACK || !"nil not black in ITDelete");
    assert((nil->maxHigh!=std::numeric_limits<N>::min())
        || !"nil->maxHigh != std::numeric_limits<N>::min() in ITDelete");
#endif
  }
  return returnValue;
}

template <typename T, typename N>
void IntervalTree<T,N>::remove(N low, N high, std::vector<T> &removed) 
{
  typename std::vector<typename IntervalTree<T,N>::Node*> got;
  fetch_node(low, high, got);
  for (typename std::vector<typename IntervalTree<T,N>::Node*>::const_iterator 
      i=got.begin(); i!=got.end(); ++i)
  {
    removed.push_back((*i)->value());
    remove(*i);
  }
}

template <typename T, typename N> template <typename F> 
void IntervalTree<T,N>::remove(N low, N high, const F &removeFunctor, std::vector<T> &removed) 
{
  typename std::vector<typename IntervalTree<T,N>::Node*> got;
  fetch_node(low, high, got);
  for (typename std::vector<typename IntervalTree<T,N>::Node*>::const_iterator 
      i=got.begin(); i!=got.end(); ++i)
  {
    if (removeFunctor((*i)->value(), (*i)->low(), (*i)->high())) {
      removed.push_back((*i)->value());
      remove(*i);
    }
  }
}

template <typename T, typename N>
void IntervalTree<T,N>::remove_window(N low, N high, std::vector<T> &removed) 
{
  typename std::vector<typename IntervalTree<T,N>::Node*> got;
  fetch_window_node(low, high, got);
  for (typename std::vector<typename IntervalTree<T,N>::Node*>::const_iterator 
      i=got.begin(); i!=got.end(); ++i)
  {
    removed.push_back((*i)->value());
    remove(*i);
  }
}

template <typename T, typename N> template <typename F>
void IntervalTree<T,N>::remove_window(
    N low, 
    N high, 
    const F& removeFunctor, 
    std::vector<T> &removed) 
{
  typename std::vector<typename IntervalTree<T,N>::Node*> got;
  fetch_window_node(low, high, got);
  for (typename std::vector<typename IntervalTree<T,N>::Node*>::const_iterator 
      i=got.begin(); i!=got.end(); ++i)
  {
    if (removeFunctor((*i)->value(), (*i)->low(), (*i)->high())) {
      removed.push_back((*i)->value());
      remove(*i);
    }
  }
}

/***********************************************************************/
/*  FUNCTION:  Overlap */
/**/
/*    INPUTS:  [a1,a2) and [b1,b2) are the low and high endpoints of two */
/*             intervals.  */
/**/
/*    OUTPUT:  stack containing pointers to the nodes between [low,high) */
/**/
/*    Modifies Input: none */
/**/
/*    EFFECT:  returns 1 if the intervals overlap, and 0 otherwise */
/***********************************************************************/

template<typename T, typename N>
N IntervalTree<T,N>::Overlap(N a1, N a2, N b1, N b2) {
  return a1 <= b2 && b1 <= a2;
}


template<typename T, typename N>
N IntervalTree<T,N>::Contain(N a1, N a2, N b1, N b2) {
  return a1 <= b1 && b2 <= a2;
}

/***********************************************************************/
/*  FUNCTION:  fetch */
/**/
/*    INPUTS:  tree is the tree to look for intervals overlapping the */
/*             interval [low,high)  */
/**/
/*    OUTPUT:  stack containing pointers to the nodes overlapping */
/*             [low,high) */
/**/
/*    Modifies Input: none */
/**/
/*    EFFECT:  Returns a stack containing pointers to nodes containing */
/*             intervals which overlap [low,high) in O(max(N,k*log(N))) */
/*             where N is the number of intervals in the tree and k is  */
/*             the number of overlapping intervals                      */
/**/
/*    Note:    This basic idea for this function comes from the  */
/*              _Introduction_To_Algorithms_ book by Cormen et al, but */
/*             modifications were made to return all overlapping intervals */
/*             instead of just the first overlapping interval as in the */
/*             book.  The natural way to do this would require recursive */
/*             calls of a basic search function.  I translated the */
/*             recursive version into an interative version with a stack */
/*             as described below. */
/***********************************************************************/



/*  The basic idea for the function below is to take the IntervalSearch */
/*  function from the book and modify to find all overlapping intervals */
/*  instead of just one. */

template<typename T, typename N>
void IntervalTree<T,N>::fetch(N low, N high, std::vector<T> &enumResultStack)  {
  typename std::vector<typename IntervalTree<T,N>::Node*> got;
  fetch_node(low, high, got);
  for (typename std::vector<typename IntervalTree<T,N>::Node*>::const_iterator 
      i = got.begin(); i != got.end(); i++) {
      enumResultStack.push_back((*i)->value());
  }
}

template<typename T, typename N>
T IntervalTree<T,N>::fetch_nearest_up(typename IntervalTree<T,N>::Node* x, N value)  {

  if(x == nil)
    return T();

  if(x->key > value) {
    // Maybe there is a better interval candidate in the left subtree
    if(x->left != nil) {
      T best_left_value = fetch_nearest_up(x->left,value);
      if (best_left_value.defined()) 
        return best_left_value;
    }
    return x->value();
  } else {
    return fetch_nearest_up(x->right,value);
  }
}

template<typename T, typename N>
T IntervalTree<T,N>::fetch_nearest_up(N value)  {
  return fetch_nearest_up(root->left,value);
}

template<typename T, typename N>
typename IntervalTree<T,N>::Node* IntervalTree<T,N>::fetch_nearest_down(typename IntervalTree<T,N>::Node* x, N value)  {

  if (x == nil)
    return NULL;

  if(x->key > value) {
    return fetch_nearest_down(x->left,value);
  } else {
    // There is not a better interval in the subtrees
    if(x->high_ == x->maxHigh && x->high_ <= value) {
      return x;
    } else {
      typename IntervalTree<T,N>::Node* best_node = NULL;
      if(x->high_ <= value) {
        best_node = x;
      }
      // Is there a closer interval in the left subtree
      if(x->left != nil) {
        typename IntervalTree<T,N>::Node* best_node_left = fetch_nearest_down(x->left,value);
        if(best_node == NULL) {
          best_node = best_node_left;
        } else if(best_node_left != NULL && best_node_left->high_ > best_node->high_) {
           best_node = best_node_left;
        }
      }
      // Is there a closer interval in the right subtree
      if(x->right != nil) {
        typename IntervalTree<T,N>::Node* best_node_right = fetch_nearest_down(x->right,value);
        if(best_node == NULL) {
          best_node = best_node_right;
        } else if(best_node_right != NULL && best_node_right->high_ > best_node->high_) {
          best_node = best_node_right;
        }
      }
      return best_node;
    }
  }
}

template<typename T, typename N>
T IntervalTree<T,N>::fetch_nearest_down(N value)  {
  typename IntervalTree<T,N>::Node* best_node = fetch_nearest_down(root->left,value);
  if(best_node)
    return best_node->value();
  else
    return T();
}


template<typename T, typename N>
void IntervalTree<T,N>::fetch_node(
    N low, 
    N high, 
    std::vector<typename IntervalTree<T,N>::Node*> &enumResultStack)  
{
  std::vector<IntervalTree<T,N>::Node*> stack;
  // left first
  stack.push_back(root->right);
  stack.push_back(root->left);
  
  while (stack.size() > 0) {
    IntervalTree<T,N>::Node* x = stack.back();
    stack.pop_back();
    if (x != nil) {
      if (Overlap(low,high,x->key,x->high_) ) {
        enumResultStack.push_back(x);
      }
      stack.push_back(x->right);
      if (x->left->maxHigh >= low) {
        stack.push_back(x->left);
      }
    }
  }
}
        
template<typename T, typename N>
void IntervalTree<T,N>::fetch_window(N low, N high, std::vector<T> &enumResultStack)  
{
  typename std::vector<typename IntervalTree<T,N>::Node*> got;
  fetch_window_node(low, high, got);
  for (typename std::vector<typename IntervalTree<T,N>::Node*>::const_iterator 
      i = got.begin(); i != got.end(); i++) {
      enumResultStack.push_back((*i)->value());
  }
}

template<typename T, typename N>
void IntervalTree<T,N>::fetch_window_node(
     N low, 
     N high, 
     std::vector<typename IntervalTree<T,N>::Node*> &enumResultStack)  
{
  std::vector<IntervalTree<T,N>::Node*> stack;
  // left first
  stack.push_back(root->right);
  stack.push_back(root->left);
  
  while (stack.size() > 0) {
    IntervalTree<T,N>::Node* x = stack.back();
    stack.pop_back();
    if (x != nil) {
      if (Contain(low,high,x->key,x->high_) ) {
        enumResultStack.push_back(x);
      }
      stack.push_back(x->right);
      if (x->left->maxHigh >= low) {
        stack.push_back(x->left);
      }
    }
  }
}

template<typename T, typename N>
bool IntervalTree<T,N>::CheckMaxHighFieldsHelper(typename IntervalTree<T,N>::Node * y, 
                                    const N currentHigh,
                                    bool match) const
{
  if (y != nil) {
    match = CheckMaxHighFieldsHelper(y->left,currentHigh,match) ?
      true : match;
    if (y->high_ == currentHigh)
      match = true;
    match = CheckMaxHighFieldsHelper(y->right,currentHigh,match) ?
      true : match;
  }
  return match;
}

          

/* Make sure the maxHigh fields for everything makes sense. *
 * If something is wrong, print a warning and exit */
template<typename T, typename N>
void IntervalTree<T,N>::CheckMaxHighFields(typename IntervalTree<T,N>::Node * x) const {
  if (x != nil) {
    CheckMaxHighFields(x->left);
    if(!(CheckMaxHighFieldsHelper(x,x->maxHigh,false) > 0)) {
      assert(0);
    }
    CheckMaxHighFields(x->right);
  }
}

template<typename T, typename N>
void IntervalTree<T,N>::check() const {
 CheckMaxHighFields(root->left);
}

#endif