Diameter of a Binary Indexed Tree with N nodes | Java implementation of the approach ; Function to find diameter of BIT with N + 1 nodes ; L is size of subtree just before subtree in which N lies ; H is the height of subtree just before subtree in which N lies ; Base Cases ; Size of subtree are power of 2 ; 3 Cases as explained in Approach ; Driver Code
class GFG { static int diameter ( int n ) { int L , H , templen ; L = 1 ; H = 0 ; if ( n == 1 ) { return 1 ; } if ( n == 2 ) { return 2 ; } if ( n == 3 ) { return 3 ; } while ( L * 2 <= n ) { L *= 2 ; H ++ ; } if ( n >= L * 2 - 1 ) return 2 * H + 1 ; else if ( n >= L + ( L / 2 ) - 1 ) return 2 * H ; return 2 * H - 1 ; } public static void main ( String [ ] args ) { int n = 15 ; System . out . println ( diameter ( n ) ) ; } }