Print all nodes that are at distance k from a leaf node | JavaScript program to print all nodes at a distance k from leaf A binary tree node ; This function prints all nodes that are distance k from a leaf node path [ ] -- > Store ancestors of a node visited [ ] -- > Stores true if a node is printed as output . A node may be k distance away from many leaves , we want to print it once ; Base case ; append this Node to the path array ; it 's a leaf, so print the ancestor at distance k only  if the ancestor is not already printed  ; If not leaf node , recur for left and right subtrees ; Given a binary tree and a nuber k , print all nodes that are k distant from a leaf ; Let us construct the tree shown in above diagram
class Node { constructor ( item ) { this . left = null ; this . right = null ; this . data = item ; } } let root ; function kDistantFromLeafUtil ( node , path , visited , pathLen , k ) { if ( node == null ) return ; path [ pathLen ] = node . data ; visited [ pathLen ] = false ; pathLen ++ ; if ( node . left == null && node . right == null && ( pathLen - k - 1 ) >= 0 && visited [ pathLen - k - 1 ] == false ) { document . write ( path [ pathLen - k - 1 ] + " " ) ; visited [ pathLen - k - 1 ] = true ; return ; } kDistantFromLeafUtil ( node . left , path , visited , pathLen , k ) ; kDistantFromLeafUtil ( node . right , path , visited , pathLen , k ) ; } function printKDistantfromLeaf ( node , k ) { let path = new Array ( 1000 ) ; path . fill ( 0 ) ; let visited = new Array ( 1000 ) ; visited . fill ( false ) ; kDistantFromLeafUtil ( node , path , visited , 0 , k ) ; } root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 4 ) ; root . left . right = new Node ( 5 ) ; root . right . left = new Node ( 6 ) ; root . right . right = new Node ( 7 ) ; root . right . left . right = new Node ( 8 ) ; document . write ( " " ) ; printKDistantfromLeaf ( root , 2 ) ;