Print nodes at k distance from root | Iterative | Node of binary tree Function to add a new node ; Function to prnodes of given level ; extra None is appended to keep track of all the nodes to be appended before level is incremented by 1 ; prwhen level is equal to k ; break the loop if level exceeds the given level number ; Driver Code ; create a binary tree
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def printKDistant ( root , klevel ) : NEW_LINE INDENT q = [ ] NEW_LINE level = 1 NEW_LINE flag = False NEW_LINE q . append ( root ) NEW_LINE q . append ( None ) NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE if ( level == klevel and temp != None ) : NEW_LINE INDENT flag = True NEW_LINE print ( temp . data , end = " ▁ " ) NEW_LINE DEDENT q . pop ( 0 ) NEW_LINE if ( temp == None ) : NEW_LINE INDENT if ( len ( q ) ) : NEW_LINE INDENT q . append ( None ) NEW_LINE DEDENT level += 1 NEW_LINE if ( level > klevel ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( temp . left ) : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT if ( temp . right ) : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE DEDENT DEDENT DEDENT print ( ) NEW_LINE return flag NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 20 ) NEW_LINE root . left = newNode ( 10 ) NEW_LINE root . right = newNode ( 30 ) NEW_LINE root . left . left = newNode ( 5 ) NEW_LINE root . left . right = newNode ( 15 ) NEW_LINE root . left . right . left = newNode ( 12 ) NEW_LINE root . right . left = newNode ( 25 ) NEW_LINE root . right . right = newNode ( 40 ) NEW_LINE print ( " data ▁ at ▁ level ▁ 1 ▁ : ▁ " , end = " " ) NEW_LINE ret = printKDistant ( root , 1 ) NEW_LINE if ( ret == False ) : NEW_LINE INDENT print ( " Number ▁ exceeds ▁ total " , " number ▁ of ▁ levels " ) NEW_LINE DEDENT print ( " data ▁ at ▁ level ▁ 2 ▁ : ▁ " , end = " " ) NEW_LINE ret = printKDistant ( root , 2 ) NEW_LINE if ( ret == False ) : NEW_LINE INDENT print ( " Number ▁ exceeds ▁ total " , " number ▁ of ▁ levels " ) NEW_LINE DEDENT print ( " data ▁ at ▁ level ▁ 3 ▁ : ▁ " , end = " " ) NEW_LINE ret = printKDistant ( root , 3 ) NEW_LINE if ( ret == False ) : NEW_LINE INDENT print ( " Number ▁ exceeds ▁ total " , " number ▁ of ▁ levels " ) NEW_LINE DEDENT print ( " data ▁ at ▁ level ▁ 6 ▁ : ▁ " , end = " " ) NEW_LINE ret = printKDistant ( root , 6 ) NEW_LINE if ( ret == False ) : NEW_LINE INDENT print ( " Number ▁ exceeds ▁ total ▁ number ▁ of ▁ levels " ) NEW_LINE DEDENT DEDENT