Java编写线段树代码
时间: 2023-01-28 20:41:22 浏览: 115
线段树代码
好的,我来帮你编写 Java 的线段树代码。
线段树是一种树形结构,其中每个节点都存储了一段区间的信息。它常常用于处理区间查询、修改等问题。
下面是一个线段树的简单实现,它可以处理区间求和问题:
```
class SegmentTree {
private static class Node {
int left;
int right;
int sum;
}
private Node[] tree;
private int[] data;
public SegmentTree(int[] data) {
this.data = data;
tree = new Node[data.length * 4];
build(0, 0, data.length - 1);
}
private void build(int treeIndex, int left, int right) {
if (left == right) {
tree[treeIndex] = new Node();
tree[treeIndex].left = left;
tree[treeIndex].right = right;
tree[treeIndex].sum = data[left];
return;
}
int mid = left + (right - left) / 2;
int leftTreeIndex = treeIndex * 2 + 1;
int rightTreeIndex = treeIndex * 2 + 2;
build(leftTreeIndex, left, mid);
build(rightTreeIndex, mid + 1, right);
tree[treeIndex] = new Node();
tree[treeIndex].left = left;
tree[treeIndex].right = right;
tree[treeIndex].sum = tree[leftTreeIndex].sum + tree[rightTreeIndex].sum;
}
public void update(int index, int value) {
update(0, index, value);
}
private void update(int treeIndex, int index, int value) {
if (tree[treeIndex].left == tree[treeIndex].right) {
tree[treeIndex].sum = value;
return;
}
int mid = tree[treeIndex].left + (tree[treeIndex].right - tree[treeIndex].left) / 2;
int leftTreeIndex = treeIndex * 2 + 1;
int rightTreeIndex = treeIndex * 2 + 2;
if (index <= mid) {
update(leftTreeIndex, index, value);
} else {
update(rightTreeIndex, index, value);
}
tree[treeIndex].sum = tree[leftTreeIndex].sum + tree[rightTreeIndex].sum;
}
public int query(int left, int right) {
return query(0, left, right);
}
private int query(int treeIndex, int left, int right) {
if (left == tree[
阅读全文