Queries for elements greater than K in the given index range using Segment Tree | Java implementation of the approach ; combine function to make parent node ; building the tree ; leaf node ; merging the nodes while backtracking ; performing query ; Out of Bounds ; completely overlaps ; partially overlaps ; Driver Code ; 1 - based indexing
public class GFG { int [ ] arr , tree ; int combine ( int a , int b ) { if ( a != 0 && b != 0 ) { return a ; } if ( a >= b ) { return a ; } return b ; } void buildTree ( int ind , int low , int high , int x ) { if ( low == high ) { if ( arr [ low ] > x ) { tree [ ind ] = arr [ low ] ; } else { tree [ ind ] = 0 ; } return ; } int mid = ( high - low ) / 2 + low ; buildTree ( 2 * ind + 1 , low , mid , x ) ; buildTree ( 2 * ind + 2 , mid + 1 , high , x ) ; tree [ ind ] = combine ( tree [ 2 * ind + 1 ] , tree [ 2 * ind + 2 ] ) ; } int query ( int ind , int low , int high , int l , int r ) { int mid = ( high - low ) / 2 + low ; if ( low > r high < l ) { return 0 ; } if ( l <= low && r >= high ) { return tree [ ind ] ; } return combine ( query ( 2 * ind + 1 , low , mid , l , r ) , query ( 2 * ind + 2 , mid + 1 , high , l , r ) ) ; } public static void main ( String args [ ] ) { GFG ob = new GFG ( ) ; ob . arr = new int [ ] { 7 , 3 , 9 , 13 , 5 , 4 } ; int n = ob . arr . length ; int k = 6 ; ob . tree = new int [ 4 * n ] ; int l = 1 , r = 4 ; ob . buildTree ( 0 , 0 , n - 1 , k ) ; System . out . println ( ob . query ( 0 , 0 , n - 1 , l - 1 , r - 1 ) ) ; } }