线段树 自己总结的模板

struct treeNode {

    int start;

    int end;

    int cover;         // 覆盖标记 -1:未覆盖  0:部分覆盖  1:完全覆盖

    treeNode *left;

    treeNode *right;

    treeNode *parent;

};


//构造线段树函数

treeNode *createTree(int start,int end)

{

    treeNode * p = new treeNode();

    if (end-start==1) {

        return NULL;

    }

    p->start = start;

    p->end=end;

    p->cover=-1;

    p->parent=NULL;

    // 生成左子树

    p->left=createTree(start, (start+end)/2);

    p->left->parent=p;

    // 生生右子树

    p->right=createTree((start+end)/2, end);

    p->right->parent=p;

    return p;

}


//覆盖线段树函数

void coverTree(treeNode* p,int start,int end)

{

    if (p->cover==1) return;

    //完全覆盖

    if (start==p->start&&end==p->end) {

        p->cover=1;

        //父段 存在的话,回溯、重新判断覆盖情况

        treeNode *temp = p;

        while (temp->parent!=NULL) {

            if (temp->parent->cover==-1) temp->parent->cover=0;

            if (temp->parent->cover==0)  temp->parent->cover=1;

            temp=temp->parent;

                

        }

        //按照我的设计,根结点的parentNULL

        if (temp->cover==-1) temp->cover=0;

        if (temp->cover==0)  temp->cover=1;

    }

    if (end <= (p->start+p->end)/2) {//向左子树 覆盖

        coverTree(p->left, start, end);

    }

    else if (start  >=(p->start+p->end)/2) //向右子树覆盖

    {

        coverTree(p->right, start, end);

    }

    else{                                   //向左、右子树覆盖

        //先向左子树覆盖

        coverTree(p->left, start, (p->start+p->end)/2);

        // 向右子树覆盖

        coverTree(p->right, (p->start+p->end)/2, end);

        

    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值