SlideShare a Scribd company logo
1 of 18
PRESENTED BY: MUZAMIL AMIN
Computer Science and Engineering
M.Tech CSE (ist sem)
Subject: Algorithms and Algorithmic complexity
topic: Segment tree
Segment tree
 Segment Tree is a basically a binary tree used for storing
the intervals or segments. Each node in the Segment Tree
represents an interval. Consider an array A of size N and
a corresponding Segment Tree T:
 The root of T will represent the whole array A[0:N−1].
 Each leaf in the Segment Tree T will represent a single
element A[i] such that 0≤i<N.
 The internal nodes in the Segment Tree T represents the
union of elementary intervals A[i:j] where 0≤i<j<N.
Continue
 The root of the Segment Tree represents the whole
array A[0:N−1]. Then it is broken down into two half intervals
or segments and the two children of the root in turn represent
the A[0:(N−1)/2] and A[(N−1)/2+1:(N−1)]. So in each step,
the segment is divided into half and the two children represent
those two halves. So the height of the segment tree will
be log2N. There are N leaves representing the N elements of
the array. The number of internal nodes is N−1. So, a total
number of nodes are 2×N−1.
 Once the Segment Tree is built, its structure cannot be
changed. We can update the values of nodes but we cannot
change its structure. Segment tree provides two operations:
Continue
 Update: To update the element of the array A and
reflect the corresponding change in the Segment
tree.
 Query: In this operation we can query on an
interval or segment and return the answer to the
problem (say minimum/maximum/summation in
the particular segment).
Segment Tree
 Construction.
 Implementation.
 Update.
 Range Sum Query.
overview
1 2 3 4 5
inde
x
0 1 2 3 4
Sum(2,4) = 12
Sum(1,3) = 9
Sum(0,4) = 15
1) Bruteforce
Time = O(N.Q)
2) Efficient
Time = O(1)
Time = O(Q)
Sum(L,R) = Sum(L-1) - Sum(R)
1 3 6 10 15
Comparison
Range sum for Q
queries
update time
Bruteforce O(N.Q) O(1)
Efficient O(Q) O(N)
Construction (Segment Tree)
Full Binary Tree: Internal nodes have 0 or 2 children & all level till 2nd last level is
completely filled
Continue
Implementation
 Implementation using array
 If current node = I
then LC = 2*i+1
RC = 2*i+2
p = [(i-1)/2]
Code for construction
int const( st, si,arr,l,r)
{
if(l==r) // leaf node
{
st[si] = arr[l];
return arr[L];
}
mid = (l+r)/2;
st[si] =const(st,2*si+1,arr,l,mid)+ const(st,2*si+2,arr,mid+1,r);
return st[si];
}
Find Range Sum
1 2 5 6 7 9
Getsum(0,0,5,2,4)
Continue
Code getsum
int getsum(si,sl,sr,l,r)
{
if (l<= sl && r>= sr) //case1: Total overlap
return st[si];
if (sr < l || sl > r) //case2: no overlap
return 0;
mid =(sl+sr)/2; //case 3:partial overlap
return getsum(st,2*si+1,arr,l,mid)+ getsum(st,2*si+2,arr,mid+1,r)
}
Update
 Update org. array
 Update seg. Tree array
1 2 5 6 7 9
Code for update
void update(si,sl,sr,pos,diff)
{
if (sl>pos || se<pos)
return;
s[si] +=diff;
if (sl!=sr)
{
mid = (sl+sr)/2;
update(2*si+1,sl,mid,pos,diff);
update(2*si+2,mid+1,pos,diff);
}
}
Time
 Construction = O(n)
 Query =O(log n)
 Update = O(log n)
 Note: segment tree is useful only if updates
are frequent. Otherwise use array
segment tree algorithm.pptx

More Related Content

What's hot

Matrices And Application Of Matrices
Matrices And Application Of MatricesMatrices And Application Of Matrices
Matrices And Application Of Matricesmailrenuka
 
Manual for the MATLAB program to solve the 2D truss
Manual for the MATLAB program to solve the 2D trussManual for the MATLAB program to solve the 2D truss
Manual for the MATLAB program to solve the 2D trussMohammaderfan Zandieh
 
Application of Matrices in real life | Matrices application | The Matrices
Application of Matrices in real life | Matrices application | The MatricesApplication of Matrices in real life | Matrices application | The Matrices
Application of Matrices in real life | Matrices application | The MatricesSahilJhajharia
 
Solving electric circuits using graph theory
Solving  electric circuits using graph theorySolving  electric circuits using graph theory
Solving electric circuits using graph theoryCheku Dojee
 
Lecture 1 test
Lecture 1 testLecture 1 test
Lecture 1 testfalcarragh
 
Single source shortestpath
Single source shortestpathSingle source shortestpath
Single source shortestpathJananiJ19
 
Learning multifractal structure in large networks (Purdue ML Seminar)
Learning multifractal structure in large networks (Purdue ML Seminar)Learning multifractal structure in large networks (Purdue ML Seminar)
Learning multifractal structure in large networks (Purdue ML Seminar)Austin Benson
 
Restoring and Non-Restoring division algo for CSE
Restoring and Non-Restoring division algo for CSERestoring and Non-Restoring division algo for CSE
Restoring and Non-Restoring division algo for CSEARoy10
 
Varaiational formulation fem
Varaiational formulation fem Varaiational formulation fem
Varaiational formulation fem Tushar Aneyrao
 
Matlab HTI summer training course Lecture3
Matlab HTI summer training course Lecture3Matlab HTI summer training course Lecture3
Matlab HTI summer training course Lecture3Mohamed Awni
 

What's hot (20)

Matrices And Application Of Matrices
Matrices And Application Of MatricesMatrices And Application Of Matrices
Matrices And Application Of Matrices
 
Lect13
Lect13Lect13
Lect13
 
Manual for the MATLAB program to solve the 2D truss
Manual for the MATLAB program to solve the 2D trussManual for the MATLAB program to solve the 2D truss
Manual for the MATLAB program to solve the 2D truss
 
Sol1
Sol1Sol1
Sol1
 
Application of Matrices in real life | Matrices application | The Matrices
Application of Matrices in real life | Matrices application | The MatricesApplication of Matrices in real life | Matrices application | The Matrices
Application of Matrices in real life | Matrices application | The Matrices
 
Unit 2
Unit 2Unit 2
Unit 2
 
Solving electric circuits using graph theory
Solving  electric circuits using graph theorySolving  electric circuits using graph theory
Solving electric circuits using graph theory
 
Division algorithm
Division algorithmDivision algorithm
Division algorithm
 
Lecture 1 test
Lecture 1 testLecture 1 test
Lecture 1 test
 
Single source shortestpath
Single source shortestpathSingle source shortestpath
Single source shortestpath
 
Application of Matrices
Application of MatricesApplication of Matrices
Application of Matrices
 
Fem in matlab
Fem in matlabFem in matlab
Fem in matlab
 
Learning multifractal structure in large networks (Purdue ML Seminar)
Learning multifractal structure in large networks (Purdue ML Seminar)Learning multifractal structure in large networks (Purdue ML Seminar)
Learning multifractal structure in large networks (Purdue ML Seminar)
 
Restoring and Non-Restoring division algo for CSE
Restoring and Non-Restoring division algo for CSERestoring and Non-Restoring division algo for CSE
Restoring and Non-Restoring division algo for CSE
 
Varaiational formulation fem
Varaiational formulation fem Varaiational formulation fem
Varaiational formulation fem
 
N41049093
N41049093N41049093
N41049093
 
Application of matrices in real life
Application of matrices in real lifeApplication of matrices in real life
Application of matrices in real life
 
Matlab HTI summer training course Lecture3
Matlab HTI summer training course Lecture3Matlab HTI summer training course Lecture3
Matlab HTI summer training course Lecture3
 
Data structures
Data structuresData structures
Data structures
 
Introduction to data mining and machine learning
Introduction to data mining and machine learningIntroduction to data mining and machine learning
Introduction to data mining and machine learning
 

Similar to segment tree algorithm.pptx

Algorithm Design and Complexity - Course 3
Algorithm Design and Complexity - Course 3Algorithm Design and Complexity - Course 3
Algorithm Design and Complexity - Course 3Traian Rebedea
 
Review session2
Review session2Review session2
Review session2NEEDY12345
 
Cs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer keyCs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer keyappasami
 
A NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREE
A NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREEA NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREE
A NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREEijscmcj
 
A NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREE
A NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREEA NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREE
A NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREEijscmc
 
5.3 dyn algo-i
5.3 dyn algo-i5.3 dyn algo-i
5.3 dyn algo-iKrish_ver2
 
Research on the Stability of the Grade Structure of a University Title
Research on the Stability of the Grade Structure of a University TitleResearch on the Stability of the Grade Structure of a University Title
Research on the Stability of the Grade Structure of a University TitleDr. Amarjeet Singh
 
Answers withexplanations
Answers withexplanationsAnswers withexplanations
Answers withexplanationsGopi Saiteja
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingzukun
 
BS LAB Manual (1).pdf
BS LAB Manual  (1).pdfBS LAB Manual  (1).pdf
BS LAB Manual (1).pdfssuser476810
 
Edge tenacity in cycles and complete
Edge tenacity in cycles and completeEdge tenacity in cycles and complete
Edge tenacity in cycles and completeijfcstjournal
 

Similar to segment tree algorithm.pptx (20)

Algorithm Design and Complexity - Course 3
Algorithm Design and Complexity - Course 3Algorithm Design and Complexity - Course 3
Algorithm Design and Complexity - Course 3
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Review session2
Review session2Review session2
Review session2
 
Daa chapter 2
Daa chapter 2Daa chapter 2
Daa chapter 2
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Cs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer keyCs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer key
 
Chapter 24 aoa
Chapter 24 aoaChapter 24 aoa
Chapter 24 aoa
 
A NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREE
A NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREEA NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREE
A NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREE
 
A NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREE
A NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREEA NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREE
A NEW PARALLEL ALGORITHM FOR COMPUTING MINIMUM SPANNING TREE
 
5.3 dyn algo-i
5.3 dyn algo-i5.3 dyn algo-i
5.3 dyn algo-i
 
Research on the Stability of the Grade Structure of a University Title
Research on the Stability of the Grade Structure of a University TitleResearch on the Stability of the Grade Structure of a University Title
Research on the Stability of the Grade Structure of a University Title
 
Answers withexplanations
Answers withexplanationsAnswers withexplanations
Answers withexplanations
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sorting
 
2.pptx
2.pptx2.pptx
2.pptx
 
BS LAB Manual (1).pdf
BS LAB Manual  (1).pdfBS LAB Manual  (1).pdf
BS LAB Manual (1).pdf
 
Lec 12.docx
Lec 12.docxLec 12.docx
Lec 12.docx
 
Cdc18 dg lee
Cdc18 dg leeCdc18 dg lee
Cdc18 dg lee
 
Edge tenacity in cycles and complete
Edge tenacity in cycles and completeEdge tenacity in cycles and complete
Edge tenacity in cycles and complete
 
Q
QQ
Q
 
06 segment trees
06 segment trees06 segment trees
06 segment trees
 

Recently uploaded

(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 

Recently uploaded (20)

(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 

segment tree algorithm.pptx

  • 1. PRESENTED BY: MUZAMIL AMIN Computer Science and Engineering M.Tech CSE (ist sem) Subject: Algorithms and Algorithmic complexity topic: Segment tree
  • 2. Segment tree  Segment Tree is a basically a binary tree used for storing the intervals or segments. Each node in the Segment Tree represents an interval. Consider an array A of size N and a corresponding Segment Tree T:  The root of T will represent the whole array A[0:N−1].  Each leaf in the Segment Tree T will represent a single element A[i] such that 0≤i<N.  The internal nodes in the Segment Tree T represents the union of elementary intervals A[i:j] where 0≤i<j<N.
  • 3. Continue  The root of the Segment Tree represents the whole array A[0:N−1]. Then it is broken down into two half intervals or segments and the two children of the root in turn represent the A[0:(N−1)/2] and A[(N−1)/2+1:(N−1)]. So in each step, the segment is divided into half and the two children represent those two halves. So the height of the segment tree will be log2N. There are N leaves representing the N elements of the array. The number of internal nodes is N−1. So, a total number of nodes are 2×N−1.  Once the Segment Tree is built, its structure cannot be changed. We can update the values of nodes but we cannot change its structure. Segment tree provides two operations:
  • 4. Continue  Update: To update the element of the array A and reflect the corresponding change in the Segment tree.  Query: In this operation we can query on an interval or segment and return the answer to the problem (say minimum/maximum/summation in the particular segment).
  • 5. Segment Tree  Construction.  Implementation.  Update.  Range Sum Query.
  • 6. overview 1 2 3 4 5 inde x 0 1 2 3 4 Sum(2,4) = 12 Sum(1,3) = 9 Sum(0,4) = 15 1) Bruteforce Time = O(N.Q) 2) Efficient Time = O(1) Time = O(Q) Sum(L,R) = Sum(L-1) - Sum(R) 1 3 6 10 15
  • 7. Comparison Range sum for Q queries update time Bruteforce O(N.Q) O(1) Efficient O(Q) O(N)
  • 9. Full Binary Tree: Internal nodes have 0 or 2 children & all level till 2nd last level is completely filled Continue
  • 10. Implementation  Implementation using array  If current node = I then LC = 2*i+1 RC = 2*i+2 p = [(i-1)/2]
  • 11. Code for construction int const( st, si,arr,l,r) { if(l==r) // leaf node { st[si] = arr[l]; return arr[L]; } mid = (l+r)/2; st[si] =const(st,2*si+1,arr,l,mid)+ const(st,2*si+2,arr,mid+1,r); return st[si]; }
  • 12. Find Range Sum 1 2 5 6 7 9 Getsum(0,0,5,2,4)
  • 14. Code getsum int getsum(si,sl,sr,l,r) { if (l<= sl && r>= sr) //case1: Total overlap return st[si]; if (sr < l || sl > r) //case2: no overlap return 0; mid =(sl+sr)/2; //case 3:partial overlap return getsum(st,2*si+1,arr,l,mid)+ getsum(st,2*si+2,arr,mid+1,r) }
  • 15. Update  Update org. array  Update seg. Tree array 1 2 5 6 7 9
  • 16. Code for update void update(si,sl,sr,pos,diff) { if (sl>pos || se<pos) return; s[si] +=diff; if (sl!=sr) { mid = (sl+sr)/2; update(2*si+1,sl,mid,pos,diff); update(2*si+2,mid+1,pos,diff); } }
  • 17. Time  Construction = O(n)  Query =O(log n)  Update = O(log n)  Note: segment tree is useful only if updates are frequent. Otherwise use array