Print nodes at k distance from root | Iterative | 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 ; create a binary tree
class Node { constructor ( data ) { this . left = null ; this . right = null ; this . data = data ; } } function newNode ( data ) { let newnode = new Node ( data ) ; return newnode ; } function printKDistant ( root , klevel ) { let q = [ ] ; let level = 1 ; let flag = false ; q . push ( root ) ; q . push ( null ) ; while ( q . length > 0 ) { let temp = q [ 0 ] ; if ( level == klevel && temp != null ) { flag = true ; document . write ( temp . data + " " ) ; } q . shift ( ) ; if ( temp == null ) { if ( q [ 0 ] != null ) q . push ( null ) ; level += 1 ; if ( level > klevel ) break ; } else { if ( temp . left != null ) q . push ( temp . left ) ; if ( temp . right != null ) q . push ( temp . right ) ; } } document . write ( " " ) ; return flag ; } let 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 ) ; document . write ( " " ) ; let ret = printKDistant ( root , 1 ) ; if ( ret == false ) document . write ( " " + " " + " " ) ; document . write ( " " ) ; ret = printKDistant ( root , 2 ) ; if ( ret == false ) document . write ( " " + " " + " " ) ; document . write ( " " ) ; ret = printKDistant ( root , 3 ) ; if ( ret == false ) document . write ( " " + " " + " " ) ; document . write ( " " ) ; ret = printKDistant ( root , 6 ) ; if ( ret == false ) document . write ( " " + " " + " " ) ;