Print all nodes that are at distance k from a leaf node | utility that allocates a new Node with the given key ; This function prints all nodes that are distance k from a leaf node path [ ] - . Store ancestors of a node visited [ ] - . Stores true if a node is printed as output . A node may be k distance away from many leaves , we want to print it once ; Base case ; append this Node to the path array ; it 's a leaf, so print the ancestor at  distance k only if the ancestor is  not already printed ; If not leaf node , recur for left and right subtrees ; Given a binary tree and a nuber k , print all nodes that are k distant from a leaf ; Driver Code ; Let us create binary tree given in the above example
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def kDistantFromLeafUtil ( node , path , visited , pathLen , k ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT path [ pathLen ] = node . key NEW_LINE visited [ pathLen ] = False NEW_LINE pathLen += 1 NEW_LINE if ( node . left == None and node . right == None and pathLen - k - 1 >= 0 and visited [ pathLen - k - 1 ] == False ) : NEW_LINE INDENT print ( path [ pathLen - k - 1 ] , end = " ▁ " ) NEW_LINE visited [ pathLen - k - 1 ] = True NEW_LINE return NEW_LINE DEDENT kDistantFromLeafUtil ( node . left , path , visited , pathLen , k ) NEW_LINE kDistantFromLeafUtil ( node . right , path , visited , pathLen , k ) NEW_LINE DEDENT def printKDistantfromLeaf ( node , k ) : NEW_LINE INDENT global MAX_HEIGHT NEW_LINE path = [ None ] * MAX_HEIGHT NEW_LINE visited = [ False ] * MAX_HEIGHT NEW_LINE kDistantFromLeafUtil ( node , path , visited , 0 , k ) NEW_LINE DEDENT MAX_HEIGHT = 10000 NEW_LINE root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE root . right . left . right = newNode ( 8 ) NEW_LINE print ( " Nodes ▁ at ▁ distance ▁ 2 ▁ are : " , end = " ▁ " ) NEW_LINE printKDistantfromLeaf ( root , 2 ) NEW_LINE