
The first line of input contains a single integer ‘T’, denoting the number of test cases.
The second line of each test case contains a positive integer ‘N’, denoting the number of nodes.
The third line of each test case contains the parent array.
The fourth line of each test case contains a node value and k value.
The first and only line of each test case contains an integer denoting the kth ancestor.
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= k <= N <= 5 * 10 ^ 4
0 <= node < N
0 <= parent[i] < N
Time limit: 1 second
This problem can be solved using a technique known as binary lifting. We need to compute each node, which is exactly 2^i nodes above a given node, and we will store it in an array up[node][i]. Now we will run a DFS to fill this for each node. To compute up[node][i], we can find the node which is 2^i-1 steps above the node which is 2^i - 1 above the current node, hence up[node][i] = up[up[node][i-1]][i-1]. Each query can be answered in log n by treating k as a binary number and moving 2^i steps upward for each set bit in k.
The steps are as follows:
Here we first traverse the binary tree and store the ancestor of each node in an array of size n. For example, suppose the array is parent[n]. Then at index i, parent[i] will store the parent of the ith node. So, the 2nd ancestor of the ith node will be parent[parent[i]] and so on. We will use this idea to calculate the kth ancestor of the given node. We can use level order traversal to populate this array.
The steps are as follows: