Skip to content

Instantly share code, notes, and snippets.

@sbsatter
Created November 5, 2020 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbsatter/82a00b7136dcd97fe8370f27aedbd9d3 to your computer and use it in GitHub Desktop.
Save sbsatter/82a00b7136dcd97fe8370f27aedbd9d3 to your computer and use it in GitHub Desktop.
Process to build a segment tree
// [left, right] => range spanned by current node
void build(int id, int left, int right) { // O (n)
if (left == right) {
// when we divide and conquer on the middle element, left and right becomes equal when we reach the leaf nodes
tree[id] = arr[left];
return;
}
int mid = (left + right)/2;
// build left child first
build(2 * id, left, mid);
// build right child next
build(2 * id + 1, mid + 1, right);
// current node sum is available from sum of left and right child
tree[id] = tree[id * 2] + tree[id * 2 + 1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment