Print all nodes that are at distance k from a leaf node | A binary tree node ; Given a binary tree and a nuber k , print all nodes that are k distant from a leaf ; Leaf node ; Parent of left leaf ; Parent of right leaf ; Driver code ; Let us construct the tree shown in above diagram
class Node { constructor ( item ) { this . data = item ; this . left = null ; this . right = null ; } } class BinaryTree { constructor ( ) { this . root = null ; } printKDistantfromLeaf ( node , k ) { if ( node == null ) return - 1 ; var lk = this . printKDistantfromLeaf ( node . left , k ) ; var rk = this . printKDistantfromLeaf ( node . right , k ) ; var isLeaf = lk == - 1 && lk == rk ; if ( lk == 0 || rk == 0 || ( isLeaf && k == 0 ) ) document . write ( " " + node . data ) ; if ( isLeaf && k > 0 ) return k - 1 ; if ( lk > 0 && lk < k ) return lk - 1 ; if ( rk > 0 && rk < k ) return rk - 1 ; return - 2 ; } } var tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 3 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 5 ) ; tree . root . right . left = new Node ( 6 ) ; tree . root . right . right = new Node ( 7 ) ; tree . root . right . left . right = new Node ( 8 ) ; document . write ( " " ) ; tree . printKDistantfromLeaf ( tree . root , 2 ) ;