// C# implementation of
// the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to add an
// edge in the tree
static void addEdge(List<int> []v,
int x, int y)
{
v[x].Add(y);
v[y].Add(x);
}
// DFS to find the Kth
// ancestor of every node
static void dfs(List<int> []tree,
List<int> temp,
int []ancestor, int u,
int parent, int k)
{
// Pushing current node
// in the vector
temp.Add(u);
// Traverse its neighbors
foreach(int i in tree[u])
{
if (i == parent)
continue;
dfs(tree, temp,
ancestor, i, u, k);
}
temp.RemoveAt(temp.Count - 1);
// If K ancestors are not
// found for current node
if (temp.Count < k)
{
ancestor[u] = -1;
}
else
{
// Add the Kth ancestor
// for the node
ancestor[u] = temp[temp.Count - k];
}
}
// Function to find Kth
// ancestor of each node
static void KthAncestor(int N, int K, int E,
int [,]edges)
{
// Building the tree
List<int> []tree = new List<int>[N + 1];
for(int i = 0; i < tree.Length; i++)
tree[i] = new List<int>();
for(int i = 0; i < E; i++)
{
addEdge(tree, edges[i, 0],
edges[i, 1]);
}
// Stores all parents of a node
List<int> temp = new List<int>();
// Store Kth ancestor
// of all nodes
int []ancestor = new int[N + 1];
dfs(tree, temp, ancestor, 1, 0, K);
// Print the ancestors
for(int i = 1; i <= N; i++)
{
Console.Write(ancestor[i] + " ");
}
}
// Driver code
public static void Main(String[] args)
{
// Given N and K
int N = 9;
int K = 2;
// Given edges of n-ary tree
int E = 8;
int [,]edges = { { 1, 2 }, { 1, 3 },
{ 2, 4 }, { 2, 5 },
{ 2, 6 }, { 3, 7 },
{ 3, 8 }, { 3, 9 } };
// Function call
KthAncestor(N, K, E, edges);
}
}
// This code is contributed by Amit Katiyar