leetcode
    image.png
    image.png

    1. class NumArray {
    2. class TreeNode{
    3. int sum;
    4. int start,end;
    5. TreeNode left,right;
    6. public TreeNode(int s,int e){
    7. left = null;
    8. right = null;
    9. start = s;
    10. end = e;
    11. }
    12. }
    13. TreeNode root = null;
    14. private TreeNode buildTree(int[] nums,int start,int end){
    15. if(start > end){
    16. return null;
    17. }
    18. TreeNode res = new TreeNode(start,end);
    19. if(start == end){
    20. res.sum = nums[start];
    21. }else{
    22. int mid = start + (end - start)/2;
    23. res.left = buildTree(nums,start,mid);
    24. res.right = buildTree(nums,mid+1,end);
    25. res.sum = res.left.sum + res.right.sum;
    26. }
    27. return res;
    28. }
    29. public NumArray(int[] nums) {
    30. root = buildTree(nums,0,nums.length - 1);
    31. }
    32. private void update(TreeNode root,int i,int val){
    33. if(root.start == root.end){
    34. root.sum = val;
    35. }else{
    36. int mid = root.start + (root.end - root.start)/2;
    37. if(i<=mid){
    38. update(root.left,i,val);
    39. }else{
    40. update(root.right,i,val);
    41. }
    42. root.sum = root.left.sum + root.right.sum;
    43. }
    44. }
    45. public void update(int index, int val) {
    46. update(root,index,val);
    47. }
    48. private int query(TreeNode root,int i,int j){
    49. if(root.start == i&&root.end == j){
    50. return root.sum;
    51. }else{
    52. int mid = root.start + (root.end - root.start)/2;
    53. if(j<=mid){
    54. return query(root.left,i,j);
    55. }else if(i>=mid+1){
    56. return query(root.right,i,j);
    57. }else{
    58. return query(root.left,i,mid) + query(root.right,mid+1,j);
    59. }
    60. }
    61. }
    62. public int sumRange(int left, int right) {
    63. return query(root,left,right);
    64. }
    65. }
    66. /**
    67. * Your NumArray object will be instantiated and called as such:
    68. * NumArray obj = new NumArray(nums);
    69. * obj.update(index,val);
    70. * int param_2 = obj.sumRange(left,right);
    71. */