Print all the leaf nodes of Binary Heap | Java implementation to print the leaf nodes of a Binary Heap ; Function to calculate height of the Binary heap with given the count of the nodes ; Function to find the leaf nodes of binary heap ; Calculate the height of the complete binary tree ; if the height if h - 1 , then there should not be any child nodes ; Function to print the leaf nodes ; Driver Code
import java . lang . * ; import java . util . * ; class GFG { static int height ( int N ) { return ( int ) Math . ceil ( Math . log ( N + 1 ) / Math . log ( 2 ) ) - 1 ; } static void findLeafNodes ( int arr [ ] , int n ) { int h = height ( n ) ; ArrayList < Integer > arrlist = new ArrayList < > ( ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( height ( i + 1 ) == h ) { arrlist . add ( arr [ i ] ) ; } else if ( height ( i + 1 ) == h - 1 && n <= ( ( 2 * i ) + 1 ) ) { arrlist . add ( arr [ i ] ) ; } else { break ; } } printLeafNodes ( arrlist ) ; } static void printLeafNodes ( ArrayList < Integer > arrlist ) { for ( int i = arrlist . size ( ) - 1 ; i >= 0 ; i -- ) { System . out . print ( arrlist . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; findLeafNodes ( arr , arr . length ) ; } }