Find K smallest leaf nodes from a given Binary Tree | Java program of the above approach ; Structure of binary tree node ; Function to create new node ; Utility function which calculates smallest three nodes of all leaf nodes ; Check if current root is a leaf node ; Traverse the left and right subtree ; Function to find the K smallest nodes of the Binary Tree ; Sorting the Leaf nodes array ; Loop to print the K smallest Leaf nodes of the array ; Driver Code ; Construct binary tree ; Function call
import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } ; static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } static Vector < Integer > storeLeaf ( Node root , Vector < Integer > arr ) { if ( root == null ) return arr ; if ( root . left == null && root . right == null ) { arr . add ( root . data ) ; return arr ; } arr = storeLeaf ( root . left , arr ) ; arr = storeLeaf ( root . right , arr ) ; return arr ; } static void KSmallest ( Node root , int k ) { Vector < Integer > arr = new Vector < Integer > ( ) ; arr = storeLeaf ( root , arr ) ; Collections . sort ( arr ) ; for ( int i = 0 ; i < k ; i ++ ) { if ( i < arr . size ( ) ) { System . out . print ( arr . get ( i ) + " ▁ " ) ; } else { break ; } } } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . left . left = newNode ( 4 ) ; root . left . left . left = newNode ( 21 ) ; root . left . right = newNode ( 5 ) ; root . left . right . right = newNode ( 8 ) ; root . right = newNode ( 3 ) ; root . right . left = newNode ( 6 ) ; root . right . right = newNode ( 7 ) ; root . right . right . right = newNode ( 19 ) ; KSmallest ( root , 3 ) ; } }