Kth ancestor of all nodes in an N | Function to add an edge in the tree ; DFS to find the Kth ancestor of every node ; Pushing current node in the vector ; Traverse its neighbors ; If K ancestors are not found for current node ; Add the Kth ancestor for the node ; Function to find Kth ancestor of each node ; Building the tree ; Stores all parents of a node ; Store Kth ancestor of all nodes ; Print the ancestors ; Driver code ; Given N and K ; Given edges of n - ary tree ; Function call
def addEdge ( v , x , y ) : NEW_LINE INDENT v [ x ] . append ( y ) NEW_LINE v [ y ] . append ( x ) NEW_LINE DEDENT def dfs ( tree , temp , ancestor , u , parent , k ) : NEW_LINE INDENT temp . append ( u ) NEW_LINE for i in tree [ u ] : NEW_LINE INDENT if ( i == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( tree , temp , ancestor , i , u , k ) NEW_LINE DEDENT temp . pop ( ) NEW_LINE if ( len ( temp ) < k ) : NEW_LINE INDENT ancestor [ u ] = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT ancestor [ u ] = temp [ len ( temp ) - k ] NEW_LINE DEDENT DEDENT def KthAncestor ( N , K , E , edges ) : NEW_LINE INDENT tree = [ [ ] for i in range ( N + 1 ) ] NEW_LINE for i in range ( E ) : NEW_LINE INDENT addEdge ( tree , edges [ i ] [ 0 ] , edges [ i ] [ 1 ] ) NEW_LINE DEDENT temp = [ ] NEW_LINE ancestor = [ 0 ] * ( N + 1 ) NEW_LINE dfs ( tree , temp , ancestor , 1 , 0 , K ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( ancestor [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 9 NEW_LINE K = 2 NEW_LINE E = 8 NEW_LINE edges = [ [ 1 , 2 ] , [ 1 , 3 ] , [ 2 , 4 ] , [ 2 , 5 ] , [ 2 , 6 ] , [ 3 , 7 ] , [ 3 , 8 ] , [ 3 , 9 ] ] NEW_LINE KthAncestor ( N , K , E , edges ) NEW_LINE DEDENT