Created
November 5, 2020 16:22
-
-
Save sbsatter/82a00b7136dcd97fe8370f27aedbd9d3 to your computer and use it in GitHub Desktop.
Process to build a segment tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// [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