可更新数据与求区间和。

    1. var NumArray = function(nums) {
    2. n = nums.length;
    3. this.segmentTree = new Array(nums.length * 4).fill(0);
    4. this.build(0, 0, n - 1, nums);
    5. console.log(this.segmentTree)
    6. };
    7. NumArray.prototype.update = function(index, val) {
    8. this.change(index, val, 0, 0, n - 1);
    9. };
    10. NumArray.prototype.sumRange = function(left, right) {
    11. return this.range(left, right, 0, 0, n - 1);
    12. };
    13. NumArray.prototype.build = function(node, s, e, nums) {
    14. if (s === e) {
    15. this.segmentTree[node] = nums[s];
    16. return;
    17. }
    18. const m = s + Math.floor((e - s) / 2);
    19. this.build(node * 2 + 1, s, m, nums);
    20. this.build(node * 2 + 2, m + 1, e, nums);
    21. this.segmentTree[node] = this.segmentTree[node * 2 + 1] + this.segmentTree[node * 2 + 2];
    22. }
    23. NumArray.prototype.change = function(index, val, node, s, e) {
    24. if (s === e) {
    25. this.segmentTree[node] = val;
    26. return;
    27. }
    28. const m = s + Math.floor((e - s) / 2);
    29. if (index <= m) {
    30. this.change(index, val, node * 2 + 1, s, m);
    31. } else {
    32. this.change(index, val, node * 2 + 2, m + 1, e);
    33. }
    34. this.segmentTree[node] = this.segmentTree[node * 2 + 1] + this.segmentTree[node * 2 + 2];
    35. }
    36. NumArray.prototype.range = function(left, right, node, s, e) {
    37. if (left === s && right === e) {
    38. return this.segmentTree[node];
    39. }
    40. const m = s + Math.floor((e - s) / 2);
    41. if (right <= m) {
    42. return this.range(left, right, node * 2 + 1, s, m);
    43. } else if (left > m) {
    44. return this.range(left, right, node * 2 + 2, m + 1, e);
    45. } else {
    46. return this.range(left, m, node * 2 + 1, s, m) + this.range(m + 1, right, node * 2 + 2, m + 1, e);
    47. }
    48. }