Giudoku Official Site
Interval tree

An interval tree is an obscure data structure: a balanced binary tree used for storing intervals.
In this page, I will present the creation of an interval tree and then a function to determine if a given interval overlaps at least one another in the tree I just built.
The building is not different from that of any other balanced binary tree that you may use. The intervals are randomly generated and then a cycle is called to determine the right position.
As stated in the comments, the parameter used for balancing is the left end of each interval (start, in the structure): if you go left, you'll read nodes with a smaller low end, and the opposite will happen if you go right.
In addition to the left and right end, every node contains a field called highInSub: it represents the highest end in the subtree rooted at that node. So this field is defined like this (let x be a random node):

highInSub(x) = max{highInSub(x->left), highInSub(x->right), x->end};

As you can see, the UpdateHighest() function does exactly what I said above, with the appropriate base conditions for NULL nodes. In fact, if the function is called with root=NULL, it means that the parent has a right node but not a left node, or viceversa; otherwise in the previous call another condition would have been triggered. This comparison must be done between the parent and the other son (which is valid): the function returns a value like -1, that can't be greater than anything in our case.
If the node is a leaf, then no further comparisons are needed: you simply return its end field.

Let's talk about Overlap. It's a rather easy function: first, x is pointed to the root. Plus, let's call I the given interval.

1
2
3
4
5
6
7
8
9
10
11
12
while (x != NULL && (low > x->end || x->start > high))
{
  if (x->left != NULL && low <= (x->left)->highInSub)
  {
    x = x->left;
  }
  else
  {
    x = x->right;
  }
}


If x is NULL, nothing has been found. If any part of the second condition (the one after the AND) is contradicted, then the root itself overlaps I and you don't need to go on further.
Otherwise, the pointer should look elsewhere. The first condition checks the left subtree: if the second part is not satisfied, you won't have any possibily to find anything there: I's start is greater than anything you will find. So you go right. Otherwise, you go left.
Question: suppose you always go left, without ever hitting the else block. How can you be sure that an overlapping interval (maybe the only one in the whole tree!) isn't present in the right subtree, and you're not missing it?

To answer this, there's a theorem that proves the correctness of the explained algorithm, divided in two parts.
Let L = {i in x->left} and R = {i in x->right} where i states for intervals. I is always the interval provided by the caller.
1. If the search goes right, the set {i in x->left that overlaps I} is void.
2. If the search goes left, then "{i in x->left that overlaps I} is void" implies "{i in x->right that overlaps I} is void too". That answers the previous doubt.

Proof: the proof is easy and uses mostly logic reasoning.
1. If (x->left == NULL) then q.e.d.. Otherwise, I can assume that low[I] > (x->left)->highInSub (if not, I would've gone left!) = high[j] for some j in L (highInSub is one of the "end" fields!). No other node in L can have an end field largest than high[j] (I don't mind who is j), for definition. Therefore, there's nothing in L that interests us: they can't even make it to our lower end! q.e.d
2. Hypotesis: I'm going left and can't find any overlapping node. So: low[I] <= (x->left)->highInSub = high[j] quite the same as before. Now, j is part of L, but it doesn't overlap for hypotesis, therefore high[I] < low[j] (given that low[I] stays "left" of the current interval, high[I] must be there too).
But, for the tree base property (it's a balanced tree) low[j] < low[k] for every k belonging to R. Thus, nothing can overlap our poor interval in the right subtree too! q.e.d

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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

/*
 * Limits for the random intervals generation
 * make sure they're all coherent
 */
#define MIN_LOW   3
#define MIN_HIGH 20

#define MAX_LOW  21
#define MAX_HIGH 40

#define NODES     5
#define TRIES     2

/*
 * A node in the interval tree
 */
struct interval
{
  int start;
  int end;
  int highInSub; /* highest value in the subtree rooted at that node */

  struct interval *left;
  struct interval *right;
};
typedef struct interval Interval;

void CreateRandomTree(Interval **);
int AddNode(Interval **, int, int);
Interval *getNewNode(int, int);
void PrintTreePreOrder(Interval *);
int UpdateHighest(Interval *);
Interval *Overlap(int, int, Interval *);
int Greater(int, int, int);
void DeleteTree(Interval *);

int main(int argc, char *argv[])
{
  int i;
  int low;
  int high;
  Interval *root = NULL;
  Interval *res;
  
  srand(time(NULL));

  CreateRandomTree(&root);
  UpdateHighest(root);

  printf("The intervals generated in the tree are:\n");
  PrintTreePreOrder(root);
  printf("\n");
  
  for (i = 1; i <= TRIES; i++)
  {
    /*
     * Generates random intervals for testing
     */
    low = MIN_LOW + rand() % MIN_HIGH;
    high = MAX_LOW + rand() % MAX_HIGH;

    printf("%d) Test interval: [%d, %d] does overlap an interval in the tree? ", i, low, high);
    res = Overlap(low, high, root);

    if (res == NULL)
    {
      printf("No\n");
    }
    else
    {
      printf("Yes, for example [%d, %d]\n", res->start, res->end);
    }
  }

  return 0;
}

/*
 * Creates a new randomly built interval tree with 5 nodes
 */
void CreateRandomTree(Interval **root)
{
  int newLow, newHigh, i;
  
  for (i = 1; i <= NODES; i++)
  {
    newLow = MIN_LOW + rand() % MIN_HIGH;
    newHigh = MAX_LOW + rand() % MAX_HIGH;

    if (AddNode(root, newLow, newHigh) != 0)
    {
      fprintf(stderr, " [**] Allocation failed! Exiting.\n");
      DeleteTree(*root); /* avoids memory leaks if something is already allocated */
      exit(-1);
    }
  }
}

/*
 * Adds the new generated node in the tree rooted at root
 * Nodes in the tree are sorted by the start parameter
 * Returns 0 on success, -1 on failure
 */
int AddNode(Interval **root, int low, int high)
{
  Interval *node = getNewNode(low, high);
  Interval *prec = NULL;
  Interval *curr = (*root);

  if (node == NULL)
  {
    return -1;
  }

  /*
   * Find the correct position for the new node.
	 */
  while (curr != NULL)
  {
    prec = curr;
    curr = (low < curr->start) ? curr->left : curr->right;
  }

  if (prec == NULL)
  {
    (*root) = node;
  }
  else
  {
    if (low < prec->start)
    {
      prec->left = node;
    }
    else
    {
      prec->right = node;
    }
  }

  return 0;
}

/*
 * Allocates a new interval with the given ends
 * The other parameters are set to default values for simplicity
 * Returns a pointer to the new node
 */
Interval *getNewNode(int l, int h)
{
  Interval *ptr = (Interval *)malloc(sizeof(Interval));

  if (ptr != NULL)
  {
    memset(ptr, 0, sizeof(Interval));
    ptr->start = l;
    ptr->end = h;
    ptr->highInSub = 0;
    ptr->right = ptr->left = NULL;
  }

  return ptr;
}

/*
 * Prints a quick representation of the new nodes
 * using a PreOrder visit (that is, parent is printed out before the children
 */
void PrintTreePreOrder(Interval *r)
{
  if (r != NULL)
  {
    printf("[%d, %d]\n", r->start, r->end);
    PrintTreePreOrder(r->left);
    PrintTreePreOrder(r->right);
  }
}

/*
 * Fills up the highInSub variable for each node
 * That field represents the highest value in the subtree rooted at the given node
 * (It's useful for the following function)
 *
 * Returns the value for the actual tree root, but will be discarded anyway
 */
int UpdateHighest(Interval *root)
{
  if (root == NULL)
  {
    return -1; /* useful if a node has a left node but not a right one, or viceversa */
  }

  if (root->left == NULL && root->right == NULL) /* leaf */
  {
    root->highInSub = root->end;
    return root->highInSub;
  }

  root->highInSub = Greater(UpdateHighest(root->left), UpdateHighest(root->right), root->end);
  return root->highInSub;
}

/*
 * Checks if the given interval [low, high] overlaps something in the tree
 * Note: overlapping means "intersecting the interval somewhere" not being a sub-interval.
 *
 * Returns the first node that corresponds to the request, or NULL if nothing is found
 */
Interval *Overlap(int low, int high, Interval *root)
{
  Interval *x = root;

  while (x != NULL && (low > x->end || x->start > high))
  {
    if (x->left != NULL && low <= (x->left)->highInSub)
    {
      x = x->left;
    }
    else
    {
      x = x->right;
    }
  }

  return x;
}

/*
 * A rather naive procedure for comparing the three integers
 */
int Greater(int n1, int n2, int n3)
{
  int max = 0;

  if (n1 > max)
  {
    max = n1;
  }
  if (n2 > max)
  {
    max = n2;
  }
  if (n3 > max)
  {
    max = n3;
  }

  return max;
}

/*
 * Deletes the tree and frees all the occupied memory
 */
void DeleteTree(Interval *root)
{
  if (root != NULL)
  {
    DeleteTree(root->left);
    DeleteTree(root->right);
    free(root);
  }
}