let newNode = function(array,left,right){
if(left == right){
return {
left,
right,
max:array[left],
min:array[left],
sum:array[left]
};
}
let mid = (left+right)/2;
mid = mid|0;
let leftChild = newNode(array,left,mid);
let rightChild = newNode(array,mid+1,right);
return {
left,
right,
max:Math.max(leftChild.max,rightChild.max),
min:Math.min(leftChild.min,rightChild.min),
sum:leftChild.sum+rightChild.sum,
leftChild,
rightChild
};
};
let query = function(node,left,right){
if(left<=node.left && right>=node.right){
return {
max:node.max,
sum:node.sum,
min:node.min
};
}else{
if(left>node.right || rightthrow new Error();
}
let mid = ((node.left+node.right)/2)|0;
if(left>mid){
return query(node.rightChild,left,right);
}else if(right<=mid){
return query(node.leftChild,left,right);
}else{
let leftRes = query(node.leftChild,left,mid);
let rightRes = query(node.rightChild,mid+1,right);
return {
max:Math.max(leftRes.max,rightRes.max),
min:Math.min(leftRes.min,rightRes.min),
sum:leftRes.sum+rightRes.sum
};
}
}
};
let update = function(node,index,value){
if(node.left == node.right){
if(node.left == index){
node.sum = value;
node.max = value;
node.min = value;
return;
}else{
throw new Error();
}
}
let mid = ((node.left+node.right)/2)|0;
if(index<=mid){
update(node.leftChild,index,value);
node.max = Math.max(node.leftChild.max,node.max);
node.min = Math.min(node.leftChild.min,node.min);
node.sum = node.leftChild.sum + node.rightChild.sum;
}else{
update(node.rightChild,index,value);
node.max = Math.max(node.rightChild.max,node.max);
node.min = Math.min(node.rightChild.min,node.min);
node.sum = node.leftChild.sum + node.rightChild.sum;
}
};
let newLineSegTree = function(array){
let root = newNode(array,0,array.length-1);
root.query = function(left,right){
if(leftroot.right){
throw new Error('给定的下标超出范围');
}
return query(root,left,right);
};
root.update = function(index,value){
index = (index|0+array.length)%array.length;
update(root,index,value);
};
return root;
};
function test(){
let array = [2,5,4,9];
let tree = newLineSegTree(array);
let res = tree.query(1,1);
tree.update(2,6);
console.info(JSON.stringify(tree,null,2));
}
test();