Vaia - The all-in-one study app.
4.8 • +11k Ratings
More than 3 Million Downloads
Free
Americas
Europe
Dive into the world of Computer Science with a deep exploration of Segment Tree - a crucial data structure offering efficient answers to multiple queries about a specific range in an array or list. This incredibly comprehensive guide steers you through the concept, application, and construction of Segment Trees, with specific attention to Python, Java, and C++ versions. As you progress, you'll uncover key aspects such as Segment Tree Lazy Propagation, 2D Segment Trees, and the comparison between Binary Indexed Trees and Segment Trees. This article is a goldmine of resources, packed with handy guides, tutorials, and examples to support your journey in mastering Segment Trees.
Explore our app and discover over 50 million learning materials for free.
Lerne mit deinen Freunden und bleibe auf dem richtigen Kurs mit deinen persönlichen Lernstatistiken
Jetzt kostenlos anmeldenDive into the world of Computer Science with a deep exploration of Segment Tree - a crucial data structure offering efficient answers to multiple queries about a specific range in an array or list. This incredibly comprehensive guide steers you through the concept, application, and construction of Segment Trees, with specific attention to Python, Java, and C++ versions. As you progress, you'll uncover key aspects such as Segment Tree Lazy Propagation, 2D Segment Trees, and the comparison between Binary Indexed Trees and Segment Trees. This article is a goldmine of resources, packed with handy guides, tutorials, and examples to support your journey in mastering Segment Trees.
A binary tree is a tree data structure in which each node has at most two children, usually designated as 'left child' and 'right child'.
In the context of a Segment Tree, an aggregate could be the sum, minimum, maximum, or any other associative operation.
if the range to be queried is completely different from the current node's range return appropriate value (max or min) if the range to be queried matches the current node's range return the value present in the current node if the range to be queried overlaps the current node's range query left child query right child combine the results
Let's say we have an array [5, 2, 3, 7]. Pre-processing the array using a Segment Tree for range sum queries will result in a tree where each node stores the sum of a specific range of the array. For instance, the root will store the sum of all elements (5+2+3+7 = 17), the left child of the root will store the sum of the first half [5, 2] = 7 and so on.
In Computer Graphics, particularly in rendering scenes, Z-buffering technique is commonly used to determine the visibility of objects. Assuming the objects are polygonal surfaces, each surface has a Z-coordinate. To find out which surface is visible (which polygon occludes others), algorithms need to find the minimum or maximum Z-coordinates quickly. Handling range queries of this sort is essentially finding the minimum or maximum in a range, which is an ideal task for Segment Trees.
The tree size is usually taken to be twice the next power of 2 of the input size for ease of implementation. This is to allow extra room for a perfectly balanced binary tree, ensuring it can accommodate every element of the input.
def buildTree(arr, tree, low, high, pos): if low == high : # Leaf node tree[pos] = arr[low] return mid = (low + high) // 2 buildTree(arr, tree, low, mid, 2 * pos + 1) # Left child buildTree(arr, tree, mid + 1, high, 2 * pos + 2) # Right child tree[pos] = min(tree[2 * pos + 1], tree[2 * pos + 2]) # Parent nodeThis code will construct a Segment Tree for range minimum queries. If one wished to construct a Segment Tree for range sum queries, you would only need to change the last line to `tree[pos] = tree[2 * pos + 1] + tree[2 * pos + 2]`.
def rangeQuery(tree, qlow, qhigh, low, high, pos): if qlow <= low and qhigh >= high: # Total overlap return tree[pos] if qlow > high or qhigh < low: # No overlap return sys.maxsize mid = (low + high) // 2 # Partial overlap return min(rangeQuery(tree, qlow, qhigh, low, mid, 2 * pos + 1), rangeQuery(tree, qlow, qhigh, mid + 1, high, 2 * pos + 2))2. **Updating the Tree:** Once your tree is built and queryable, you need to know how to update values. This is performed by identifying the node to be updated and then updating the path from the leaf node to the root. Here is a simple Python function to update the Segment Tree:
def updateTree(arr, tree, low, high, idx, val, pos): if low == high: # Leaf Node arr[idx] = val tree[pos] = val else: mid = (low + high) // 2 if low <= idx and idx <= mid: # idx in left child updateTree(arr, tree, low, mid, idx, val, 2 * pos + 1) else: # idx in right child updateTree(arr, tree, mid + 1, high, idx, val, 2 * pos + 2) tree[pos] = min(tree[2 * pos + 1], tree[2 * pos + 2]) # Parent nodeThis function updates the tree for a change in the array at a specific index (idx) with a new value (val). To change it for a range sum tree, change the last line to `tree[pos] = tree[2 * pos + 1] + tree[2 * pos + 2]`. Remember to always understand the logic behind each operation and modify the functions according to your specific needs (sum, min, max, etc). Working with Segment Trees in Python can be a daunting task, but with understanding and practice, you can grasp this advanced data structure with ease. Don't forget that Segment Trees are an optimisation technique and may not always be necessary, but having a good grasp of them will surely strengthen your algorithm and data structure understanding!
void buildTree(int arr[], int start, int end, int tree[], int node) { if (start == end) { // Leaf node will have a single element tree[node] = arr[start]; } else { int mid = (start + end) / 2; // Recurse on the left child buildTree(arr, start, mid, tree, 2*node+1); // Recurse on the right child buildTree(arr, mid+1, end, tree, 2*node+2); // Internal node will have the sum of both of its children tree[node] = tree[2*node+1] + tree[2*node+2]; } }This function constructs a Segment Tree for range sum queries. To adapt it for a minimum or maximum range query, replace `tree[node] = tree[2*node+1] + tree[2*node+2]` with the appropriate operation.
int rangeQuery(int tree[], int start, int end, int l, int r, int node) { if (l <= start && r >= end) // Inside the query range return tree[node]; if (end < l || start > r) // Outside the query range return 0; int mid = (start + end) / 2; // Partial overlap return rangeQuery(tree, start, mid, l, r, 2*node+1) + rangeQuery(tree, mid+1, end, l, r, 2*node+2); }For min or max queries, change the return statement `return 0` for cases outside the query range to a suitable value ( e.g., `Integer.MAX_VALUE` or `Integer.MIN_VALUE`) and modify the aggregate operation to min or max respectively. 2. **Updating the Tree:** Each update operation impacts the path from the leaf to the root of the tree. This happens as an update to an array element changes the aggregate value stored in nodes along the path. Here's how you can update a Segment Tree in Java:
void updateNode(int tree[], int start, int end, int idx, int diff, int node) { if (idx < start || idx > end) // If the input index lies outside the range of this segment return; tree[node] = tree[node] + diff; // Update // If a non-leaf node if (end != start) { int mid = (start + end) / 2; updateNode(tree, start, mid, idx, diff, 2*node + 1); updateNode(tree, mid+1, end, idx, diff, 2*node + 2); } }In the function, `diff` represents the difference with which the array element at `idx` is updated. If you're not performing a sum operation, remember to adapt your code accordingly. In conclusion, Segment Trees provide a significant advantage when there is a need to handle dynamic range queries efficiently. Their construction and manipulation can seem complex but with practice, their mastery can open up a deeper understanding of data structures and insert you ahead in your coding journey. Java, with its robustness and functionality, is a wonderful language to explore this concept in great depth and detail.
Here's a simple C++ function to build a Segment Tree:
void buildTree(int arr[], int* tree, int start, int end, int treeNode) { if(start == end) { tree[treeNode] = arr[start]; return; } int mid = (start + end) / 2; buildTree(arr, tree, start, mid, 2*treeNode); buildTree(arr, tree, mid+1, end, 2*treeNode+1); tree[treeNode] = tree[2*treeNode] + tree[2*treeNode+1]; }
This function will create a Segment Tree for the sum of a given range. If you wish to build a Segment Tree for min or max queries, replace `tree[treeNode] = tree[2*treeNode] + tree[2*treeNode+1];` with the appropriate operation.
Let's plunge into the operations of the Segment Tree.
Take a look at this exemplary C++ function for executing a range query:
int rangeQuery(int* tree, int start, int end, int left, int right, int treeNode) { if(start > right || end < left) { // Completely outside given range return INT32_MAX; } if(start >= left && end <= right) { // Completely inside given range return tree[treeNode]; } // Partially inside and partially outside int mid = (start + end) / 2; int option1 = rangeQuery(tree, start, mid, left, right, 2*treeNode); int option2 = rangeQuery(tree, mid+1, end, left, right, 2*treeNode+1); return min(option1, option2); }
This function returns the minimum in a given range. If you wish to fetch the sum or maximum, replace `return min(option1, option2);` with the sum or maximum operation and adjust the base case accordingly.
Examine this C++ function:
void updateTree(int* arr, int* tree, int start, int end, int idx, int value, int treeNode) { if(start == end) { // Leaf Node arr[idx] = value; tree[treeNode] = value; return; } int mid = (start + end) / 2; if(idx > mid) { // If idx is in right subtree updateTree(arr, tree, mid+1, end, idx, value, 2*treeNode+1); } else { // If idx is in left subtree updateTree(arr, tree, start, mid, idx, value, 2*treeNode); } tree[treeNode] = tree[2*treeNode] + tree[2*treeNode+1]; }
This code shows how to update the Segment Tree for a given index with a new value. For other aggregate operations like min or max replace `tree[treeNode] = tree[2*treeNode] + tree[2*treeNode+1];` with the appropriate operation.
In essence, Lazy Propagation is a strategy of postponing certain batch updates to speed up query operations. Instead of immediately updating all relevant nodes, Lazy Propagation records the updates and only applies them when the affected nodes are queried.
def rangeUpdate(st, lazy, l, r, diff, start, end, node): # Propagating any pending update if lazy[node] != 0: st[node] += (end - start + 1) * lazy[node] if start != end: # Not a leaf node lazy[2*node + 1] += lazy[node] lazy[2*node + 2] += lazy[node] lazy[node] = 0 # Reset the node # If current segment is outside the range if start > end or start > r or end < l: return # If current segment is fully in range if start >= l and end <= r: st[node] += (end - start + 1) * diff if start != end: # Not a leaf node lazy[2*node + 1] += diff lazy[2*node + 2] += diff return # If current segment is partially in range mid = (start + end) // 2 rangeUpdate(st, lazy, l, r, diff, start, mid, 2*node + 1) rangeUpdate(st, lazy, l, r, diff, mid+1, end, 2*node + 2) st[node] = st[2*node + 1] + st[2*node + 2]
A 2D Segment Tree is essentially a Segment Tree of Segment Trees. It's constructed by first creating a Segment Tree where each node stores another Segment Tree. The primary tree is built based on rows of the matrix, and each nested Segment Tree corresponds to a particular row's column values.
Consider a 2D matrix `mat` and a 2D Segment Tree `tree`:
def buildTree(mat, tree, rowStart, rowEnd, colStart, colEnd, node): if rowStart == rowEnd: if colStart == colEnd: # Leaf node tree[node] = mat[rowStart][colStart] else: # Merge the child nodes at the secondary (column) level midCol = (colStart + colEnd) // 2 buildTree(mat, tree, rowStart, rowEnd, colStart, midCol, 2*node) buildTree(mat, tree, rowStart, rowEnd, midCol+1, colEnd, 2*node+1) tree[node] = tree[2*node] + tree[2*node+1] else: # Merge the child nodes midRow = (rowStart + rowEnd) // 2 buildTree(mat, tree, rowStart, midRow, colStart, colEnd, 2*node) buildTree(mat, tree, midRow+1, rowEnd, colStart, colEnd, 2*node+1) tree[node] = tree[2*node] + tree[2*node+1]
This function assumes `mat` is square and `tree` has already been allocated memory. It constructs a 2D Segment Tree storing sums of sub-matrices, but can be adapted for any other aggregate operation.
Aspect | Segment Tree | Binary Indexed Tree |
Complexity | Higher | Lower |
Type of Queries and Updates | More versatile | More limited |
Construction and Operation | More complex, uses recursion | Simpler, does not use recursion |
Space efficiency | Less space-efficient | More space-efficient |
Flashcards in Segment Tree12
Start learningWhat is a Segment Tree and what is its purpose?
A Segment Tree is a data structure that enables efficient management of range queries and updates. It's a type of binary tree where each node corresponds to an aggregate of child node values, ideal for handling an array's different ranges effectively.
What are the practical applications of Segment Trees?
Segment Trees are used in computer graphics to efficiently find min or max Z coordinates, in database systems to speed up range aggregate operations, and in geospatial data for efficient geographical range searching.
What is the process of constructing a Segment Tree in Python?
The construction of a Segment Tree in Python starts by initialising a tree with size based on the input size (usually twice the next power of 2 of the input size). Then, recursion is used to build the tree by breaking down the array into smaller sub-arrays, solving individual sub-problems and merging them.
How do you operate and use a Segment Tree in Python after it is constructed?
You can operate a Segment Tree in Python by making range queries and updating the values. For range queries, you traverse the tree and return the required aggregate for a given range. For updating values, you identify the node to be updated, then update the path from the leaf node to the root.
What are the key steps in constructing a Segment Tree using Java?
The construction of a Segment Tree involves initializing the Segment Tree as an array and then recursively dividing the original array into two equal halves. Further, we construct the left and right subtree in a post-order fashion until we reach a single element array. In every step, we compute the aggregate from the left and right subtree and store it in the parent node.
How can one perform range queries and update operations on a Segment Tree in Java?
Range queries involve locating the aggregate of elements in a specified range and can be executed using a specific Java code snippet. Updating the tree impacts the path from the leaf to the root, as an update to an array element changes the aggregate value stored in nodes along the path. Another Java code snippet can be used for this operation.
Already have an account? Log in
The first learning app that truly has everything you need to ace your exams in one place
Sign up to highlight and take notes. It’s 100% free.
Save explanations to your personalised space and access them anytime, anywhere!
Sign up with Email Sign up with AppleBy signing up, you agree to the Terms and Conditions and the Privacy Policy of Vaia.
Already have an account? Log in