段树

时间:2017-10-30 05:13:01

标签: c++ memory tree

我正在实现段树类,它可以成功编译。但是,当我运行一些测试用例时,它总是会抛出“分段错误11”之类的错误。如果我在OJ上运行它,它会抛出:

第60行:未对齐地址0x000000000005内的成员访问类型'struct SumTree',需要8字节对齐

有人可以帮帮我吗?我想也许它与内存分配有关,甚至我用

memset(left,0,sizeof(left));

它仍然不起作用。我不太擅长C ++中的内存分配,如果可以的话,请向我推荐一些材料供我学习。

谢谢!

代码:

struct SumTree {
    int val,start,end;
    SumTree* left;
    SumTree* right;
    SumTree(int a, int b): val(0), start(a), end(b), left(NULL), right(NULL) {

    }
};

class NumArray {
public:
    NumArray(vector<int> nums) {
        size=nums.size();
        root=buildTree(nums,0,size-1);
    }

    void update(int i, int val) {
        update(root,i,val);
    }

    int sumRange(int i, int j) {
        i=max(i,0);
        j=min(j,size-1);
        return getSum(i,j,root);
    }
private:
    int size;
    SumTree* root;
    SumTree* buildTree(vector<int> nums, int a, int b) {
        SumTree* root=new SumTree(a,b);
        if (a==b) {
            root->val=nums[a];
            return root;
        }
        int mid=a+(b-a)/2;
        root->left=buildTree(nums,a,mid);
        root->right=buildTree(nums,mid+1,b);
        root->val=root->left->val+root->right->val;
        return root;
    }
    int update(SumTree* root, int index, int k) {
        int diff;
        if (root->start==index && root->end==index) {
            diff=k-root->val;
            root->val=k;
            return diff;
        }
        int mid=root->start+(root->end-root->start)/2;
        if (mid<index) {
            diff=update(root->right,index,k);
        }
        else {
            diff=update(root->left,index,k);
        }
        root->val+=diff;
        return diff;
    }
    int getSum(int a, int b, SumTree* root) {
        int res=0;
        if (root->start==a && root->end==b) return root->val; // Line 60
        int mid=root->start+(root->end-root->start)/2;
        if (mid<a) return getSum(a,b,root->right);
        if (mid>=b) return getSum(a,b,root->left);
        return getSum(a,mid,root->left)+getSum(mid+1,b,root->right);
    }
};

0 个答案:

没有答案