0

Suppose there's an array with n = 5

int [] arr = {1,2,3,4,5};

and

int [] segmentTree = new int[n*4];

Here's the code for building this segmentTree

buildSegmentTree(a , 1 , 0 , n-1);

void buildSegmentTree(int [] a  , int vertex , int leftLimit , int rightLimit)
{    
     if(leftLimit == rightLimit)
     segmentTree[vertex] = a[leftLimit];
     else
     {
          int mid = (leftLimit + rightLimit)/2;
          //Builds the left part of the Segment Tree
          buildSegmentTree(a , vertex * 2 , leftLimit , mid);
          //Builds the right part of the Segment Tree
          buildSegmentTree(a , vertex*2 + 1 , mid+1 , rightLimit);
          segmentTree[vertex] = segmentTree[vertex*2] + segmentTree[vertex*2 + 1];
     }
}

When I print the values of the Segment Tree this is the output that I get

0 15 6 9 3 3 4 5 1 2 0 0 0 0 0 0 0 0 0 0

I understand what these values mean (for example 15 is the sum of 6 and 9), but I dont understand how are they getting stored and how are the calls getting executed.

Zarc
  • 11
  • 2
  • 2
    So your question is how do I debug a function? The answer is simple: `Console.WriteLine`. It's your friend, use it whenever you want to see what's being executed. Additionally, [add a breakpoint](https://learn.microsoft.com/en-us/visualstudio/debugger/using-breakpoints?view=vs-2019), and step through the code. See exactly what is executing, and how it's executing. – Blue Oct 14 '19 at 06:22

1 Answers1

0

You can understand it easily by building tree on a paper.
Keep in mind:
If node has (0 , n-1) interval then, left child has (0 , mid) and right child is (mid+1, n-1).

According to the array given arr, take the interval (0,4) as it is the very first node you have. Now by finding middle of that interval we made two child : left one is (0,2) and other one is (3,4). Now it looks like below:
                (0 , 4)
                /       \
         (0 , 2)     (3 , 4)
Now similarly, split left child and right child as well until we get leftLimit=rightLimit so the final tree looks like:
                               (0 , 4)
                              /         \
                    (0 , 2)           (3 , 4)
                    /       \           /         \
          (0 , 1)    (2 , 2)   (3 , 3)     (4 , 4)
          /       \
  (0 , 0)       (1 , 1)

The sum of 0th and 1th element of the arr i.e, 1 and 2 get stored in node with interval (0,1), sum of (0,1) and (2,2) get stored in (0,2) and so on.

In this way tree will build with root element containing the sum of whole array arr. For more details go through the link
https://www.hackerearth.com/practice/data-structures/advanced-data-structures/segment-trees/tutorial/
Hope it will make sense and will be helpful :)