线段树是一棵二叉搜索树,与普通的二叉搜索树最大的差别是每个节点都表示的是一个线段,有一个起点和终点。
建立线段树的时间复杂度是O(n),查询和删除的复杂度都是O(logN)。
定义节点来表示一个线段
typedef struct node{
int start;//线段开始
int end;//线段结束
int mid;//线段中值,标准的线段树是没有这个值的,我加入这个值方便运算
int count;//线段被覆盖的次数
struct node* left;//左子树
struct node* right;//右子树
}node;
简要写一下插入操作的实现:
void insert(int start, int end, node* cur){
if(start==cur->start&&end==cur->end){//如果恰好覆盖到该节点
++cur->count;
return ;
}
else if(start>=cur->start&&end<=cur->mid)//如果在当前节点的左侧
insert(start,cur->mid,cur->left);
else if(start>=cur->mid&&end<=cur->end)//如果在当前节点的右侧
insert(cur->mid+1;end,cur->right);
else{//如果跨越了当前节点
insert(start,cur->mid,cur->left);
insert(cur->mid+1,end,cur->right);
}
}