|
| 1 | +# Kth Ancestor in a Tree |
| 2 | +## Medium |
| 3 | +<div class="problems_problem_content__Xm_eO"><p><span style="font-size: 18px;">Given a binary tree of size <strong>N</strong>, a <strong>node,</strong> and a positive integer <strong>k</strong>., Your task is to complete the function <strong>kthAncestor()</strong>, the function should return the <strong>kth</strong> ancestor of the given node in the binary tree. If there does not exist any such ancestor then return -1.<br><strong>Note</strong>: It is guaranteed that the <strong>node</strong> exists in the tree.</span></p> |
| 4 | +<p><span style="font-size: 18px;"><strong>Example 1:</strong></span></p> |
| 5 | +<pre><span style="font-size: 18px;"> |
| 6 | +<img style="height: 230px; width: 287px;" src="https://contribute.geeksforgeeks.org/wp-content/uploads/reverse.jpg" alt=""> |
| 7 | +<strong>Input:</strong> |
| 8 | +K = 2 Node = 4 |
| 9 | +<strong>Output:</strong> 1 |
| 10 | +<strong>Explanation:</strong> |
| 11 | +Since, K is 2 and node is 4, so we |
| 12 | +first need to locate the node and |
| 13 | +look k times its ancestors. |
| 14 | +Here in this Case node 4 has 1 as his |
| 15 | +2nd Ancestor aka the Root of the tree.</span></pre> |
| 16 | +<p><strong><span style="font-size: 18px;">Example 2:</span></strong></p> |
| 17 | +<pre><span style="font-size: 18px;"><strong>Input:</strong> |
| 18 | +k=1 </span> |
| 19 | +<span style="font-size: 18px;">node=3 |
| 20 | + 1 |
| 21 | + / \</span> |
| 22 | + <span style="font-size: 18px;">2 3</span> |
| 23 | + |
| 24 | +<span style="font-size: 18px;"><strong>Output:</strong> |
| 25 | +1 |
| 26 | +<strong>Explanation: |
| 27 | +</strong>K=1 and node=3 ,Kth ancestor of node 3 is 1.</span></pre> |
| 28 | +<p><span style="font-size: 18px;"><strong>Your Task:</strong><br>You are asked to complete the function <strong>kthAncestor()</strong> which accepts <strong>root</strong> of the tree, <strong>k</strong> and <strong>node</strong> as input parameters, and returns the <strong>kth ancestor </strong>of Node which contains node as its value.</span></p> |
| 29 | +<p><span style="font-size: 18px;"><strong>Expected Time Complexity:</strong> O(N)<br><strong>Expected Auxiliary Space:</strong> O(N)</span></p> |
| 30 | +<p><span style="font-size: 18px;"><strong>Constraints:</strong><br>1<=N<=10<sup>5</sup><sup><br></sup></span><span style="font-size: 18px;">1<= K <= 100<br>1 <= Node.data <= N</span></p></div> |
0 commit comments