Print nodes at k distance from root | Iterative | C # 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 added to keep track of all the nodes to be added 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
using System ; using System . Collections . Generic ; class GFG { public class Node { public int data ; public Node left , right ; } static Node newNode ( int data ) { Node newnode = new Node ( ) ; newnode . data = data ; newnode . left = newnode . right = null ; return newnode ; } static Boolean printKDistant ( Node root , int klevel ) { Queue < Node > q = new Queue < Node > ( ) ; int level = 1 ; Boolean flag = false ; q . Enqueue ( root ) ; q . Enqueue ( null ) ; while ( q . Count > 0 ) { Node temp = q . Peek ( ) ; if ( level == klevel && temp != null ) { flag = true ; Console . Write ( temp . data + " ▁ " ) ; } q . Dequeue ( ) ; if ( temp == null ) { if ( q . Count > 0 && q . Peek ( ) != null ) q . Enqueue ( null ) ; level += 1 ; if ( level > klevel ) break ; } else { if ( temp . left != null ) q . Enqueue ( temp . left ) ; if ( temp . right != null ) q . Enqueue ( temp . right ) ; } } Console . Write ( " STRNEWLINE " ) ; return flag ; } public static void Main ( String [ ] srga ) { 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 ) ; Console . Write ( " data ▁ at ▁ level ▁ 1 ▁ : ▁ " ) ; Boolean ret = printKDistant ( root , 1 ) ; if ( ret == false ) Console . Write ( " Number ▁ exceeds ▁ total ▁ " + " number ▁ of ▁ levels STRNEWLINE " ) ; Console . Write ( " data ▁ at ▁ level ▁ 2 ▁ : ▁ " ) ; ret = printKDistant ( root , 2 ) ; if ( ret == false ) Console . Write ( " Number ▁ exceeds ▁ total ▁ " + " number ▁ of ▁ levels STRNEWLINE " ) ; Console . Write ( " data ▁ at ▁ level ▁ 3 ▁ : ▁ " ) ; ret = printKDistant ( root , 3 ) ; if ( ret == false ) Console . Write ( " Number ▁ exceeds ▁ total ▁ " + " number ▁ of ▁ levels STRNEWLINE " ) ; Console . Write ( " data ▁ at ▁ level ▁ 6 ▁ : ▁ " ) ; ret = printKDistant ( root , 6 ) ; if ( ret == false ) Console . Write ( " Number ▁ exceeds ▁ total " + " number ▁ of ▁ levels STRNEWLINE " ) ; } }