Given a binary tree of size **N**, a **node** and a positive integer **K**., your task is to complete the function **kthAncestor()**, the function should return the **Kth** ancestor of the given node in the binary tree. If there does not exist any such ancestor then return -1.

Example:

Input: K = 2 Node = 4 Output: 1 Since, K is 2 and node is 4, so we first need to locate the node and look k times its ancestors. Here in this Case node 4 has 1 as his 2nd Ancestor aka the Root of the tree.

**Input:**

The function takes three arguments as input, first the reference pointer to the **root** of the binary tree, second an integer variable **K** denoting the kth ancestor and last the integer variable **Node**, denoting the node whose ancestor is to be located.

There will be **T**, test cases and for each test case the function will be called separately.

**Output:**

For each test the function should return the Kth ancestor of the given Node form the binary tree.

**Constraints:**

1<=T<=500

1<=N<=10^{3}

**Example:
Input:**

2

2

1 2 L 1 3 R

1 3

4

1 2 L 1 3 R 2 4 L 2 5 R

2 4

1

1

Author: harshitsidhwa

If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.

Sulagna | 117 |

RUTVIKHARIPARA | 116 |

janvidavda105190 | 93 |

harshsiddhapura105461 | 93 |

madhursengar24 | 86 |

PiyushPandey4 | 617 |

ASWATHAMA | 561 |

akhyasharma01 | 547 |

john_wick | 521 |

jagrit_07 | 448 |

blackshadows | 5362 |

Ibrahim Nash | 5242 |

akhayrutdinov | 5111 |

mb1973 | 4929 |

Quandray | 4598 |

Login to report an issue on this page.