Print all nodes that are at distance k from a leaf node | C ++ program to print all nodes at a distance k from leaf ; A binary tree node ; Given a binary tree and a number 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> data = key ; temp -> left = temp -> right = NULL ; return temp ; } int printKDistantfromLeaf ( struct Node * node , int k ) { if ( node == NULL ) return -1 ; int lk = printKDistantfromLeaf ( node -> left , k ) ; int rk = printKDistantfromLeaf ( node -> right , k ) ; bool isLeaf = lk == -1 && lk == rk ; if ( lk == 0 || rk == 0 || ( isLeaf && k == 0 ) ) cout << ( " ▁ " ) << ( 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 ; } int main ( ) { Node * root = NULL ; root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> right -> left -> right = newNode ( 8 ) ; cout << ( " ▁ Nodes ▁ at ▁ distance ▁ 2 ▁ are ▁ : " ) << endl ; printKDistantfromLeaf ( root , 2 ) ; }