Print nodes at k distance from root | Iterative | CPP program to print all nodes of level k iterative approach ; Node of binary tree ; Function to add a new node ; Function to print nodes of given level ; extra NULL is pushed to keep track of all the nodes to be pushed before level is incremented by 1 ; print when level is equal to k ; break the loop if level exceeds the given level number ; Driver code ; create a binary tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * newnode = new Node ( ) ; newnode -> data = data ; newnode -> left = newnode -> right = NULL ; } bool printKDistant ( Node * root , int klevel ) { queue < Node * > q ; int level = 1 ; bool flag = false ; q . push ( root ) ; q . push ( NULL ) ; while ( ! q . empty ( ) ) { Node * temp = q . front ( ) ; if ( level == klevel && temp != NULL ) { flag = true ; cout << temp -> data << " ▁ " ; } q . pop ( ) ; if ( temp == NULL ) { if ( q . front ( ) ) q . push ( NULL ) ; level += 1 ; if ( level > klevel ) break ; } else { if ( temp -> left ) q . push ( temp -> left ) ; if ( temp -> right ) q . push ( temp -> right ) ; } } cout << endl ; return flag ; } int main ( ) { Node * root = newNode ( 20 ) ; root -> left = newNode ( 10 ) ; root -> right = newNode ( 30 ) ; root -> left -> left = newNode ( 5 ) ; root -> left -> right = newNode ( 15 ) ; root -> left -> right -> left = newNode ( 12 ) ; root -> right -> left = newNode ( 25 ) ; root -> right -> right = newNode ( 40 ) ; cout << " data ▁ at ▁ level ▁ 1 ▁ : ▁ " ; int ret = printKDistant ( root , 1 ) ; if ( ret == false ) cout << " Number ▁ exceeds ▁ total ▁ number ▁ of ▁ levels STRNEWLINE " ; cout << " data ▁ at ▁ level ▁ 2 ▁ : ▁ " ; ret = printKDistant ( root , 2 ) ; if ( ret == false ) cout << " Number ▁ exceeds ▁ total ▁ number ▁ of ▁ levels STRNEWLINE " ; cout << " data ▁ at ▁ level ▁ 3 ▁ : ▁ " ; ret = printKDistant ( root , 3 ) ; if ( ret == false ) cout << " Number ▁ exceeds ▁ total ▁ number ▁ of ▁ levels STRNEWLINE " ; cout << " data ▁ at ▁ level ▁ 6 ▁ : ▁ " ; ret = printKDistant ( root , 6 ) ; if ( ret == false ) cout << " Number ▁ exceeds ▁ total ▁ number ▁ of ▁ levels STRNEWLINE " ; return 0 ; }