Sunday 16 August 2015

Segment Tree Implementation in C++

1. buildTree function creates the segment tree.
2. getSum() function return the sum.


 #include<bits/stdc++.h>  
 #include "iostream"  
 using namespace std;  
 class node{  
 public:  
      int data;  
      int l,r;  
      node* left,*right;  
 };  
 node* newNode(int data,int l,int r){  
      node* newN = new node;  
      newN->data = data;  
      newN->l = l;  
      newN->r = r; 
     newN->left = NULL;
     newN->right = NULL; 
 return newN;  
 }  
 int operationOnData(int data1,int data2){  
      return data1+data2;  
 }  
 node* buildTree(int arr[],int l,int r)  
 {  
      if(l>r) return NULL;  
      node* nd;  
      if(l==r)  
           nd = newNode(arr[l],l,r);  
      else{  
           nd = newNode(0,l,r);  
           int mid = (l+r)/2;  
           nd->left = buildTree(arr,l,mid);  
           nd->right = buildTree(arr,mid+1,r);  
           nd->data = operationOnData(nd->left->data,nd->right->data);  
      }  
      return nd;  
 }  
 int getSum(node* root,int l, int r){  
      if(root->l>=l && root->r<=r){  
           return root->data;  
      }  
      else  
      if(root->r<l ||root->l>r)  
           return 0;   
      else  
           return getSum(root->right,l,r)+getSum(root->left,l,r);  
 }  
 void update(node* root,int arr[],int index,int newValue,int l,int r)  
 {  
      if(l>r) return;  
      if(!root) return;  
      if(l==r && l == index)  
           root->data = newValue;  
      else{  
           int mid = (l+r)/2;  
           update(root->left,arr,index,newValue, l,mid);  
           update(root->right,arr,index,newValue,mid+1,r);  
           int left =0,right=0;  
           if(root->left) left = root->left->data;  
           if(root->right) right = root->right->data;  
           if(left || right)  
           root->data = operationOnData(left,right);  
      }  
 }  
 int height(node* root)  
 {  
      if(root==NULL) return 0;  
      int lHeight = height(root->left);  
      int rHeight = height(root->right);  
      return lHeight>rHeight?lHeight+1:rHeight+1;  
 }  
 void printLevel(node* root,int d)  
 {  
      if(root==NULL) return;  
      if(d==1) cout<<root->data<<" "<<root->l<<" "<<root->r<<endl;  
      printLevel(root->left,d-1);  
      printLevel(root->right,d-1);  
 }  
 void levelorder(node* root)  
 {  
      for(int d =1; d<=height(root) ;d++)  
           printLevel(root,d);  
 }  
 int main()  
 {  
       int arr[] = {1, 3, 5, 7, 9,11};  
         int n=sizeof(arr)/sizeof(int);  
         node* root = buildTree(arr,0,n-1);  
         update(root,arr,0,3,0,n-1);  
        cout<<getSum(root,0,1);  
 }  

No comments:

Post a Comment