# K-th ancestor of a node in Binary Tree

Given a binary tree in which nodes are numbered from 1 to n. Given a node and a positive integer K. We have to print the K-th ancestor of the given node in the binary tree. If there does not exist any such ancestor then print -1.

For example in the below given binary tree, 2nd ancestor of node 4 and 5 is 1. 3rd ancestor of node 4 will be -1. ## Recommended: Please solve it on PRACTICE first, before moving on to the solution.

The idea to do this is to first traverse the binary tree and store the ancestor of each node in an array of size n. For example, suppose the array is anecestor[n]. Then at index i, ancestor[i] will store the ancestor of ith node. So, the 2nd ancestor of ith node will be ancestor[ancestor[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 of ancestors.

Below is the implementation of above idea.

## C++

 `/* C++ program to calculate Kth ancestor of given node */` `#include ` `#include ` `using` `namespace` `std; ` `  `  `// A Binary Tree Node ` `struct` `Node ` `{ ` `    ``int` `data; ` `    ``struct` `Node *left, *right; ` `}; ` ` `  `// fucntion to generate array of ancestors ` `void` `generateArray(Node *root, ``int` `ancestors[]) ` `{ ` `    ``// There will be no ancestor of root node ` `    ``ancestors[root->data] = -1; ` ` `  `    ``// level order traversal to  ` `    ``// generate 1st ancestor ` `    ``queue q; ` `    ``q.push(root); ` ` `  `    ``while``(!q.empty()) ` `    ``{ ` `        ``Node* temp  = q.front(); ` `        ``q.pop(); ` ` `  `        ``if` `(temp->left) ` `        ``{ ` `            ``ancestors[temp->left->data] = temp->data; ` `            ``q.push(temp->left); ` `        ``} ` ` `  `        ``if` `(temp->right) ` `        ``{ ` `            ``ancestors[temp->right->data] = temp->data; ` `            ``q.push(temp->right); ` `        ``} ` `    ``}  ` `} ` ` `  `// function to calculate Kth ancestor ` `int` `kthAncestor(Node *root, ``int` `n, ``int` `k, ``int` `node) ` `{ ` `    ``// create array to store 1st ancestors ` `    ``int` `ancestors[n+1] = {0}; ` ` `  `    ``// generate first ancestor array ` `    ``generateArray(root,ancestors); ` ` `  `    ``// variable to track record of number of ` `    ``// ancestors visited ` `    ``int` `count = 0; ` ` `  `    ``while` `(node!=-1) ` `    ``{    ` `        ``node = ancestors[node]; ` `        ``count++; ` ` `  `        ``if``(count==k) ` `            ``break``; ` `    ``} ` ` `  `    ``// print Kth ancestor ` `    ``return` `node; ` `}  ` ` `  `// Utility function to create a new tree node ` `Node* newNode(``int` `data) ` `{ ` `    ``Node *temp = ``new` `Node; ` `    ``temp->data = data; ` `    ``temp->left = temp->right = NULL; ` `    ``return` `temp; ` `} ` `  `  `// Driver program to test above functions ` `int` `main() ` `{ ` `    ``// Let us create binary tree shown in above diagram ` `    ``Node *root = newNode(1); ` `    ``root->left = newNode(2); ` `    ``root->right = newNode(3); ` `    ``root->left->left = newNode(4); ` `    ``root->left->right = newNode(5); ` `  `  `    ``int` `k = 2; ` `    ``int` `node = 5; ` ` `  `    ``// print kth ancestor of given node ` `    ``cout<

## Java

 `/* Java program to calculate Kth ancestor of given node */` `import` `java.util.*;  ` `class` `GfG { ` `// A Binary Tree Node  ` `static` `class` `Node  ` `{  ` `    ``int` `data;  ` `    ``Node left, right;  ` `} ` ` `  `// fucntion to generate array of ancestors  ` `static` `void` `generateArray(Node root, ``int` `ancestors[])  ` `{  ` `    ``// There will be no ancestor of root node  ` `    ``ancestors[root.data] = -``1``;  ` ` `  `    ``// level order traversal to  ` `    ``// generate 1st ancestor  ` `    ``Queue q = ``new` `LinkedList ();  ` `    ``q.add(root);  ` ` `  `    ``while``(!q.isEmpty())  ` `    ``{  ` `        ``Node temp = q.peek();  ` `        ``q.remove();  ` ` `  `        ``if` `(temp.left != ``null``)  ` `        ``{  ` `            ``ancestors[temp.left.data] = temp.data;  ` `            ``q.add(temp.left);  ` `        ``}  ` ` `  `        ``if` `(temp.right != ``null``)  ` `        ``{  ` `            ``ancestors[temp.right.data] = temp.data;  ` `            ``q.add(temp.right);  ` `        ``}  ` `    ``}  ` `}  ` ` `  `// function to calculate Kth ancestor  ` `static` `int` `kthAncestor(Node root, ``int` `n, ``int` `k, ``int` `node)  ` `{  ` `    ``// create array to store 1st ancestors  ` `    ``int` `ancestors[] = ``new` `int``[n + ``1``];  ` ` `  `    ``// generate first ancestor array  ` `    ``generateArray(root,ancestors);  ` ` `  `    ``// variable to track record of number of  ` `    ``// ancestors visited  ` `    ``int` `count = ``0``;  ` ` `  `    ``while` `(node!=-``1``)  ` `    ``{  ` `        ``node = ancestors[node];  ` `        ``count++;  ` ` `  `        ``if``(count==k)  ` `            ``break``;  ` `    ``}  ` ` `  `    ``// print Kth ancestor  ` `    ``return` `node;  ` `}  ` ` `  `// Utility function to create a new tree node  ` `static` `Node newNode(``int` `data)  ` `{  ` `    ``Node temp = ``new` `Node();  ` `    ``temp.data = data;  ` `    ``temp.left = ``null``; ` `    ``temp.right = ``null``;  ` `    ``return` `temp;  ` `}  ` ` `  `// Driver program to test above functions  ` `public` `static` `void` `main(String[] args)  ` `{  ` `    ``// Let us create binary tree shown in above diagram  ` `    ``Node root = newNode(``1``);  ` `    ``root.left = newNode(``2``);  ` `    ``root.right = newNode(``3``);  ` `    ``root.left.left = newNode(``4``);  ` `    ``root.left.right = newNode(``5``);  ` ` `  `    ``int` `k = ``2``;  ` `    ``int` `node = ``5``;  ` ` `  `    ``// print kth ancestor of given node  ` `    ``System.out.println(kthAncestor(root,``5``,k,node));  ` `} ` `}  `

## Python3

 `"""Python3 program to calculate Kth ancestor ` `   ``of given node """` ` `  `# A Binary Tree Node  ` `# Utility function to create a new tree node  ` `class` `newNode:  ` ` `  `    ``# Constructor to create a newNode  ` `    ``def` `__init__(``self``, data):  ` `        ``self``.data ``=` `data  ` `        ``self``.left ``=` `None` `        ``self``.right ``=` `None` ` `  `# fucntion to generate array of ancestors  ` `def` `generateArray(root, ancestors):  ` ` `  `    ``# There will be no ancestor of root node  ` `    ``ancestors[root.data] ``=` `-``1` ` `  `    ``# level order traversal to  ` `    ``# generate 1st ancestor  ` `    ``q ``=` `[]  ` `    ``q.append(root)  ` ` `  `    ``while``(``len``(q)): ` `        ``temp ``=` `q[``0``]  ` `        ``q.pop(``0``)  ` ` `  `        ``if` `(temp.left): ` `            ``ancestors[temp.left.data] ``=` `temp.data  ` `            ``q.append(temp.left)  ` `     `  `        ``if` `(temp.right): ` `            ``ancestors[temp.right.data] ``=` `temp.data  ` `            ``q.append(temp.right)  ` ` `  `# function to calculate Kth ancestor  ` `def` `kthAncestor(root, n, k, node): ` `     `  `    ``# create array to store 1st ancestors  ` `    ``ancestors ``=` `[``0``] ``*` `(n ``+` `1``) ` ` `  `    ``# generate first ancestor array  ` `    ``generateArray(root,ancestors)  ` ` `  `    ``# variable to track record of number  ` `    ``# of ancestors visited  ` `    ``count ``=` `0` ` `  `    ``while` `(node !``=` `-``1``) : ` `        ``node ``=` `ancestors[node] ` `        ``count ``+``=` `1` `        ``if``(count ``=``=` `k): ` `            ``break` `             `  `    ``# prKth ancestor  ` `    ``return` `node ` `                         `  `# Driver Code ` `if` `__name__ ``=``=` `'__main__'``: ` ` `  `    ``# Let us create binary tree shown  ` `    ``# in above diagram  ` `    ``root ``=` `newNode(``1``)  ` `    ``root.left ``=` `newNode(``2``)  ` `    ``root.right ``=` `newNode(``3``)  ` `    ``root.left.left ``=` `newNode(``4``)  ` `    ``root.left.right ``=` `newNode(``5``)  ` `     `  `    ``k ``=` `2` `    ``node ``=` `5` ` `  `    ``# prkth ancestor of given node  ` `    ``print``(kthAncestor(root, ``5``, k, node)) ` ` `  `# This code is contributed by  ` `# SHUBHAMSINGH10 `

## C#

 `/* C# program to calculate Kth ancestor of given node */` `using` `System; ` `using` `System.Collections.Generic; ` ` `  `class` `GfG  ` `{ ` `     `  `// A Binary Tree Node  ` `public` `class` `Node  ` `{  ` `    ``public` `int` `data;  ` `    ``public` `Node left, right;  ` `} ` ` `  `// fucntion to generate array of ancestors  ` `static` `void` `generateArray(Node root, ``int` `[]ancestors)  ` `{  ` `    ``// There will be no ancestor of root node  ` `    ``ancestors[root.data] = -1;  ` ` `  `    ``// level order traversal to  ` `    ``// generate 1st ancestor  ` `    ``LinkedList q = ``new` `LinkedList ();  ` `    ``q.AddLast(root);  ` ` `  `    ``while``(q.Count != 0)  ` `    ``{  ` `        ``Node temp = q.First.Value;  ` `        ``q.RemoveFirst();  ` ` `  `        ``if` `(temp.left != ``null``)  ` `        ``{  ` `            ``ancestors[temp.left.data] = temp.data;  ` `            ``q.AddLast(temp.left);  ` `        ``}  ` ` `  `        ``if` `(temp.right != ``null``)  ` `        ``{  ` `            ``ancestors[temp.right.data] = temp.data;  ` `            ``q.AddLast(temp.right);  ` `        ``}  ` `    ``}  ` `}  ` ` `  `// function to calculate Kth ancestor  ` `static` `int` `kthAncestor(Node root, ``int` `n, ``int` `k, ``int` `node)  ` `{  ` `    ``// create array to store 1st ancestors  ` `    ``int` `[]ancestors = ``new` `int``[n + 1];  ` ` `  `    ``// generate first ancestor array  ` `    ``generateArray(root,ancestors);  ` ` `  `    ``// variable to track record of number of  ` `    ``// ancestors visited  ` `    ``int` `count = 0;  ` ` `  `    ``while` `(node != -1)  ` `    ``{  ` `        ``node = ancestors[node];  ` `        ``count++;  ` ` `  `        ``if``(count == k)  ` `            ``break``;  ` `    ``}  ` ` `  `    ``// print Kth ancestor  ` `    ``return` `node;  ` `}  ` ` `  `// Utility function to create a new tree node  ` `static` `Node newNode(``int` `data)  ` `{  ` `    ``Node temp = ``new` `Node();  ` `    ``temp.data = data;  ` `    ``temp.left = ``null``; ` `    ``temp.right = ``null``;  ` `    ``return` `temp;  ` `}  ` ` `  `// Driver program to test above functions  ` `public` `static` `void` `Main(String[] args)  ` `{  ` `    ``// Let us create binary tree shown in above diagram  ` `    ``Node root = newNode(1);  ` `    ``root.left = newNode(2);  ` `    ``root.right = newNode(3);  ` `    ``root.left.left = newNode(4);  ` `    ``root.left.right = newNode(5);  ` ` `  `    ``int` `k = 2;  ` `    ``int` `node = 5;  ` ` `  `    ``// print kth ancestor of given node  ` `    ``Console.WriteLine(kthAncestor(root,5,k,node));  ` `} ` `}  ` ` `  `// This code has been contributed by 29AjayKumar `

Output:

```1
```

Time Complexity : O( n )
Auxiliary Space : O( n )

This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

3

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.