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 program to test the above functions ; Let us construct the tree shown in above diagram
class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; int printKDistantfromLeaf ( Node node , int k ) { if ( node == null ) return - 1 ; int lk = printKDistantfromLeaf ( node . left , k ) ; int rk = printKDistantfromLeaf ( node . right , k ) ; boolean isLeaf = lk == - 1 && lk == rk ; if ( lk == 0 || rk == 0 || ( isLeaf && k == 0 ) ) System . out . print ( " ▁ " + 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 ; } public static void main ( String args [ ] ) { BinaryTree 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 ) ; System . out . println ( " ▁ Nodes ▁ at ▁ distance ▁ 2 ▁ are ▁ : " ) ; tree . printKDistantfromLeaf ( tree . root , 2 ) ; } }