Build a segment tree for N-ary rooted tree
Prerequisite: Segment tree and depth first search.
In this article, an approach to convert an N-ary rooted tree( a tree with more than 2 children) into a segment tree is discussed which is used to perform a range update queries.
Why do we need a segment tree when we already have an n-ary rooted tree?
Many times, a situation occurs where the same operation has to be performed on multiple nodes and their subtrees along with query operations multiple times.
Let’s say that we have to perform N updates on different subtrees. Every operation can take up to O(N) time as it is an N-ary tree so overall complexity will be O(N^2) which is too slow to process more than 10^3 updates queries. So we have to go the other way around and we will build a segment tree for the same.
Approach: A depth first search is performed to walk through all the nodes and keep the track of the indexes of the subtree of every node in a converted array using two arrays tin and tout(which will be the range to do updates and queries). The DFS will perform a Euler walk. The idea is to create an array and add nodes to it in the order they get visited to the converted array.
Let’s see how the tin and tout arrays help in determining the range in the converted array.
Let N-ary rooted tree be:
real values on nodes: 1 2 2 1 4 3 6 converted arr(indexes): 1 2 3 5 6 7 4 Node 3 has three children 5, 6, 7. Therefore, the range of node 3 is index 3-6. NODE: RANGE(tin-tout) NODE 1: 1 - 7 NODE 2: 2 - 2 NODE 3: 3 - 6 NODE 5: 4 - 4 NODE 6: 5 - 5 NODE 7: 6 - 6 NODE 4: 7 - 7
Here, Node 1 has a range from 1-7 (all nodes) so the update and query will be performed on all the nodes. Leaf nodes like 2 which have no children will only update range 2-2(only itself) this proves that our range arrays tin and tout are correct. Similarly, tin and tout for all the nodes determine the range for query and update in the segment tree.
The following is the implementation of the approach:
sum at node 1: 19 sum at node 2: 2 sum at node 3: 15 sum at node 4: 1 sum at node 5: 4 sum at node 6: 3 sum at node 7: 6 After Update sum at node 1: 20 sum at node 2: 2 sum at node 3: 16 sum at node 4: 1 sum at node 5: 4 sum at node 6: 4 sum at node 7: 4