Find K smallest leaf nodes from a given Binary Tree | 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 ; Construct binary tree ; Function call
class Node { constructor ( data ) { this . left = null ; this . right = null ; this . data = data ; } } function newNode ( data ) { let temp = new Node ( data ) ; return temp ; } function storeLeaf ( root , arr ) { if ( root == null ) return arr ; if ( root . left == null && root . right == null ) { arr . push ( root . data ) ; return arr ; } arr = storeLeaf ( root . left , arr ) ; arr = storeLeaf ( root . right , arr ) ; return arr ; } function KSmallest ( root , k ) { let arr = [ ] ; arr = storeLeaf ( root , arr ) ; arr . sort ( function ( a , b ) { return a - b } ) ; for ( let i = 0 ; i < k ; i ++ ) { if ( i < arr . length ) { document . write ( arr [ i ] + " " ) ; } else { break ; } } } let 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 ) ;