human
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"
Solution in Python:
 Write me a code to kth ancestor of all nodes in an N and the other steps required?
assistant
#Here is code to kth ancestor of all nodes in an N and the other steps required.
 def addEdge ( v , x , y ) :
	v [ x ] . append ( y )
	v [ y ] . append ( x )
def dfs ( tree , temp , ancestor , u , parent , k ) :
	temp . append ( u )
	for i in tree [ u ] :
		if ( i == parent ) :
			continue
		dfs ( tree , temp , ancestor , i , u , k )
	temp . pop ( )
	if ( len ( temp ) < k ) :
		ancestor [ u ] = - 1
	else :
		ancestor [ u ] = temp [ len ( temp ) - k ]
def KthAncestor ( N , K , E , edges ) :
	tree = [ [ ] for i in range ( N + 1 ) ]
	for i in range ( E ) :
		addEdge ( tree , edges [ i ] [ 0 ] , edges [ i ] [ 1 ] )
	temp = [ ]
	ancestor = [ 0 ] * ( N + 1 )
	dfs ( tree , temp , ancestor , 1 , 0 , K )
	for i in range ( 1 , N + 1 ) :
		print ( ancestor [ i ] , end = " ▁ " )
if __name__ == ' _ _ main _ _ ' :
	N = 9
	K = 2
	E = 8
	edges = [ [ 1 , 2 ] , [ 1 , 3 ] , [ 2 , 4 ] , [ 2 , 5 ] , [ 2 , 6 ] , [ 3 , 7 ] , [ 3 , 8 ] , [ 3 , 9 ] ]
	KthAncestor ( N , K , E , edges )