interval tree source code in c
时间: 2023-12-23 12:02:36 浏览: 70
Sure! Here's an example of an interval tree implemented in C:
```c
#include <stdio.h>
#include <stdlib.h>
// Structure to represent an interval
struct Interval {
int low, high;
};
// Structure to represent a node in the interval tree
struct Node {
struct Interval *interval;
int max;
struct Node *left, *right;
};
// Function to create a new interval tree node
struct Node* newNode(struct Interval i) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->interval = (struct Interval*)malloc(sizeof(struct Interval));
node->interval->low = i.low;
node->interval->high = i.high;
node->max = i.high;
node->left = NULL;
node->right = NULL;
return node;
}
// Function to insert a new interval into the interval tree
struct Node* insert(struct Node* root, struct Interval i) {
if (root == NULL)
return newNode(i);
int l = root->interval->low;
if (i.low < l)
root->left = insert(root->left, i);
else
root->right = insert(root->right, i);
if (root->max < i.high)
root->max = i.high;
return root;
}
// Function to check if two intervals overlap
int doOverlap(struct Interval i1, struct Interval i2) {
return (i1.low <= i2.high && i2.low <= i1.high);
}
// Function to search for overlapping intervals in the interval tree
void search(struct Node* root, struct Interval i) {
if (root == NULL)
return;
if (doOverlap(*(root->interval), i))
printf("Overlaps with [%d, %d]\n", root->interval->low, root->interval->high);
if (root->left != NULL && root->left->max >= i.low)
search(root->left, i);
search(root->right, i);
}
// Example usage
int main() {
struct Interval intervals[] = {{15, 20}, {10, 30}, {17, 19},
{5, 20}, {12, 15}, {30, 40}};
int n = sizeof(intervals) / sizeof(intervals[0]);
struct Node* root = NULL;
for (int i = 0; i < n; i++)
root = insert(root, intervals[i]);
struct Interval x = {14, 16};
search(root, x);
return 0;
}
```
This code implements an interval tree data structure in C. It includes functions to create a new interval tree node, insert an interval into the tree, check if two intervals overlap, and search for overlapping intervals in the tree. The main function provides an example usage of the interval tree.
阅读全文