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.
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 ancestor[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++
#include <iostream>
#include <queue>
using namespace std;
struct Node
{
int data;
struct Node *left, *right;
};
void generateArray(Node *root, int ancestors[])
{
ancestors[root->data] = -1;
queue<Node*> 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);
}
}
}
int kthAncestor(Node *root, int n, int k, int node)
{
int ancestors[n+1] = {0};
generateArray(root,ancestors);
int count = 0;
while (node!=-1)
{
node = ancestors[node];
count++;
if (count==k)
break ;
}
return node;
}
Node* newNode( int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
int main()
{
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;
cout<<kthAncestor(root,5,k,node);
return 0;
}
|
Java
import java.util.*;
class GfG {
static class Node
{
int data;
Node left, right;
}
static void generateArray(Node root, int ancestors[])
{
ancestors[root.data] = - 1 ;
Queue<Node> q = new LinkedList<Node> ();
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);
}
}
}
static int kthAncestor(Node root, int n, int k, int node)
{
int ancestors[] = new int [n + 1 ];
generateArray(root,ancestors);
int count = 0 ;
while (node!=- 1 )
{
node = ancestors[node];
count++;
if (count==k)
break ;
}
return node;
}
static Node newNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.left = null ;
temp.right = null ;
return temp;
}
public static void main(String[] args)
{
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 ;
System.out.println(kthAncestor(root, 5 ,k,node));
}
}
|
Python3
class newNode:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def generateArray(root, ancestors):
ancestors[root.data] = - 1
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)
def kthAncestor(root, n, k, node):
ancestors = [ 0 ] * (n + 1 )
generateArray(root,ancestors)
count = 0
while (node ! = - 1 ) :
node = ancestors[node]
count + = 1
if (count = = k):
break
return node
if __name__ = = '__main__' :
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
print (kthAncestor(root, 5 , k, node))
|
C#
using System;
using System.Collections.Generic;
class GfG
{
public class Node
{
public int data;
public Node left, right;
}
static void generateArray(Node root, int []ancestors)
{
ancestors[root.data] = -1;
LinkedList<Node> q = new LinkedList<Node> ();
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);
}
}
}
static int kthAncestor(Node root, int n, int k, int node)
{
int []ancestors = new int [n + 1];
generateArray(root,ancestors);
int count = 0;
while (node != -1)
{
node = ancestors[node];
count++;
if (count == k)
break ;
}
return node;
}
static Node newNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.left = null ;
temp.right = null ;
return temp;
}
public static void Main(String[] args)
{
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;
Console.WriteLine(kthAncestor(root,5,k,node));
}
}
|
Javascript
<script>
class Node
{
constructor()
{
this .data = 0;
this .left = null ;
this .right = null ;
}
}
function generateArray(root, ancestors)
{
ancestors[root.data] = -1;
var q = [];
q.push(root);
while (q.length != 0)
{
var temp = q[0];
q.shift();
if (temp.left != null )
{
ancestors[temp.left.data] = temp.data;
q.push(temp.left);
}
if (temp.right != null )
{
ancestors[temp.right.data] = temp.data;
q.push(temp.right);
}
}
}
function kthAncestor(root, n, k, node)
{
var ancestors = Array(n+1).fill(0);
generateArray(root,ancestors);
var count = 0;
while (node != -1)
{
node = ancestors[node];
count++;
if (count == k)
break ;
}
return node;
}
function newNode(data)
{
var temp = new Node();
temp.data = data;
temp.left = null ;
temp.right = null ;
return temp;
}
var root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
var k = 2;
var node = 5;
document.write(kthAncestor(root,5,k,node));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2: In this method first we will get an element whose ancestor has to be searched and from that node, we will decrement count one by one till we reach that ancestor node.
for example –
consider the tree given below:-
(1)
/ \
(4) (2)
/ \ \
(3) (7) (6)
\
(8)
Then check if k=0 if yes then return that element as an ancestor else climb a level up and reduce k (k = k-1).
Initially k = 2
First we search for 8 then,
at 8 => check if(k == 0) but k = 2 so k = k-1 => k = 2-1 = 1 and climb a level up i.e. at 7
at 7 => check if(k == 0) but k = 1 so k = k-1 => k = 1-1 = 0 and climb a level up i.e. at 4
at 4 => check if(k == 0) yes k = 0 return this node as ancestor.
Implementation:
C++14
< div id= "highlighter_73341" class = "syntaxhighlighter nogutter " ><table border= "0" cellpadding= "0" cellspacing= "0" ><tbody><tr><td class = "code" >< div class = "container" >< div class = "line number1 index0 alt2" ><code class = "comments" >
|
Java
<div id= "highlighter_31437" class = "syntaxhighlighter nogutter " ><table border= "0" cellpadding= "0" cellspacing= "0" ><tbody><tr><td class = "code" ><div class = "container" ><div class = "line number1 index0 alt2" ><code class = "comments" >
|
Python3
class node:
def __init__( self , data):
self .left = None
self .right = None
self .data = data
def ancestor(root, item):
global k
if (root = = None ):
return False
if (root.data = = item):
k = k - 1
return True
else :
flag = ancestor(root.left, item);
if (flag):
if (k = = 0 ):
print ( "[" + str (root.data) + "]" , end = ' ' )
return False
k = k - 1
return True
flag2 = ancestor(root.right, item)
if (flag2):
if (k = = 0 ):
print ( "[" + str (root.data) + "]" )
return False
k = k - 1
return True
if __name__ = = "__main__" :
root = node( 1 )
root.left = node( 4 )
root.left.right = node( 7 )
root.left.left = node( 3 )
root.left.right.left = node( 8 )
root.right = node( 2 )
root.right.right = node( 6 )
item = 3
k = 1
loc = k
flag = ancestor(root, item)
if (flag):
print ( "Ancestor doesn't exist" )
else :
print ( "is the " + str (loc) +
"th ancestor of [" + str (item) + "]" )
|
C#
using System;
public class Node
{
public int data;
public Node left, right;
public Node( int x)
{
this .data = x;
this .left = this .right = null ;
}
}
class GFG{
static int k = 1;
static bool ancestor(Node root, int item)
{
if (root == null )
return false ;
if (root.data == item)
{
k = k - 1;
return true ;
}
else
{
bool flag = ancestor(root.left, item);
if (flag)
{
if (k == 0)
{
Console.Write( "[" + root.data + "] " );
return false ;
}
k = k - 1;
return true ;
}
bool flag2 = ancestor(root.right, item);
if (flag2)
{
if (k == 0)
{
Console.Write( "[" + root.data + "] " );
return false ;
}
k = k - 1;
return true ;
}
}
return false ;
}
static public void Main()
{
Node root = new Node(1);
root.left = new Node(4);
root.left.right = new Node(7);
root.left.left = new Node(3);
root.left.right.left = new Node(8);
root.right = new Node(2);
root.right.right = new Node(6);
int item = 3;
int loc = k;
bool flag = ancestor(root, item);
if (flag)
Console.WriteLine( "Ancestor doesn't exist" );
else
Console.WriteLine( "is the " + (loc) +
"th ancestor of [" +
(item) + "]" );
}
}
|
Javascript
<div id= "highlighter_335838" class= "syntaxhighlighter nogutter " ><table border= "0" cellpadding= "0" cellspacing= "0" ><tbody><tr><td class= "code" ><div class= "container" ><div class= "line number1 index0 alt2" ><code class= "plain" ><script> </code></div><div class= "line number2 index1 alt1" ><code class= "undefined spaces" > </code> </div><div class= "line number3 index2 alt2" ><code class= "plain" >class Node </code></div><div class= "line number4 index3 alt1" ><code class= "plain" >{ </code></div><div class= "line number5 index4 alt2" ><code class= "undefined spaces" > </code><code class= "plain" >constructor(x) </code></div><div class= "line number6 index5 alt1" ><code class= "undefined spaces" > </code><code class= "plain" >{ </code></div><div class= "line number7 index6 alt2" ><code class= "undefined spaces" > </code><code class= "keyword" > this </code><code class= "plain" >.data=x; </code></div><div class= "line number8 index7 alt1" ><code class= "undefined spaces" > </code><code class= "keyword" > this </code><code class= "plain" >.left = </code><code class= "keyword" > this </code><code class= "plain" >.right = </code><code class= "keyword" > null </code><code class= "plain" >; </code></div><div class= "line number9 index8 alt2" ><code class= "undefined spaces" > </code><code class= "plain" >} </code></div><div class= "line number10 index9 alt1" ><code class= "plain" >} </code></div><div class= "line number11 index10 alt2" ><code class= "undefined spaces" > </code> </div><div class= "line number12 index11 alt1" ><code class= "keyword" > function </code> <code class= "plain" >ancestor(root, item) </code></div><div class= "line number13 index12 alt2" ><code class= "plain" >{ </code></div><div class= "line number14 index13 alt1" ><code class= "undefined spaces" > </code><code class= "keyword" > if </code> <code class= "plain" >(root == </code><code class= "keyword" > null </code><code class= "plain" >) </code></div><div class= "line number15 index14 alt2" ><code class= "undefined spaces" > </code><code class= "plain" >{ </code></div><div class= "line number16 index15 alt1" ><code class= "undefined spaces" > </code><code class= "keyword" > return </code> <code class= "keyword" > false </code><code class= "plain" >; </code></div><div class= "line number17 index16 alt2" ><code class= "undefined spaces" > </code><code class= "plain" >} </code></div><div class= "line number18 index17 alt1" ><code class= "undefined spaces" > </code> </div><div class= "line number19 index18 alt2" ><code class= "undefined spaces" > </code><code class= "keyword" > if </code> <code class= "plain" >(root.data == item) </code></div><div class= "line number20 index19 alt1" ><code class= "undefined spaces" > </code><code class= "plain" >{ </code></div><div class= "line number21 index20 alt2" ><code class= "undefined spaces" > </code><code class= "plain" >k = k - 1; </code></div><div class= "line number22 index21 alt1" ><code class= "undefined spaces" > </code><code class= "keyword" > return </code> <code class= "keyword" > true </code><code class= "plain" >; </code></div><div class= "line number23 index22 alt2" ><code class= "undefined spaces" > </code><code class= "plain" >} </code></div><div class= "line number24 index23 alt1" ><code class= "undefined spaces" > </code> </div><div class= "line number25 index24 alt2" ><code class= "undefined spaces" > </code><code class= "keyword" > else </code></div><div class= "line number26 index25 alt1" ><code class= "undefined spaces" > </code><code class= "plain" >{ </code></div><div class= "line number27 index26 alt2" ><code class= "undefined spaces" > </code><code class= "plain" >let flag = ancestor(root.left, item); </code></div><div class= "line number28 index27 alt1" ><code class= "undefined spaces" > </code><code class= "keyword" > if </code> <code class= "plain" >(flag) </code></div><div class= "line number29 index28 alt2" ><code class= "undefined spaces" > </code><code class= "plain" >{ </code></div><div class= "line number30 index29 alt1" ><code class= "undefined spaces" > </code><code class= "keyword" > if </code> <code class= "plain" >(k == 0) </code></div><div class= "line number31 index30 alt2" ><code class= "undefined spaces" > </code><code class= "plain" >{ </code></div><div class= "line number32 index31 alt1" ><code class= "undefined spaces" > </code><code class= "plain" >document.write(</code><code class= "string" > "[" </code> <code class= "plain" >+ (root.data) + </code><code class= "string" > "] " </code><code class= "plain" >); </code></div><div class= "line number33 index32 alt2" ><code class= "undefined spaces" > </code><code class= "keyword" > return </code> <code class= "keyword" > false </code><code class= "plain" >; </code></div><div class= "line number34 index33 alt1" ><code class= "undefined spaces" > </code><code class= "plain" >} </code></div><div class= "line number35 index34 alt2" ><code class= "undefined spaces" > </code><code class= "plain" >k = k - 1; </code></div><div class= "line number36 index35 alt1" ><code class= "undefined spaces" > </code><code class= "keyword" > return </code> <code class= "keyword" > true </code><code class= "plain" >; </code></div><div class= "line number37 index36 alt2" ><code class= "undefined spaces" > </code><code class= "plain" >} </code></div><div class= "line number38 index37 alt1" ><code class= "undefined spaces" > </code><code class= "plain" >let flag2 = ancestor(root.right, item); </code></div><div class= "line number39 index38 alt2" ><code class= "undefined spaces" > </code><code class= "keyword" > if </code> <code class= "plain" >(flag2) </code></div><div class= "line number40 index39 alt1" ><code class= "undefined spaces" > </code><code class= "plain" >{ </code></div><div class= "line number41 index40 alt2" ><code class= "undefined spaces" > </code><code class= "keyword" > if </code> <code class= "plain" >(k == 0) </code></div><div class= "line number42 index41 alt1" ><code class= "undefined spaces" > </code><code class= "plain" >{ </code></div><div class= "line number43 index42 alt2" ><code class= "undefined spaces" > </code><code class= "plain" >document.write(</code><code class= "string" > "[" </code> <code class= "plain" >+ (root.data) + </code><code class= "string" > "] " </code><code class= "plain" >); </code></div><div class= "line number44 index43 alt1" ><code class= "undefined spaces" > </code><code class= "keyword" > return </code> <code class= "keyword" > false </code><code class= "plain" >; </code></div><div class= "line number45 index44 alt2" ><code class= "undefined spaces" > </code><code class= "plain" >} </code></div><div class= "line number46 index45 alt1" ><code class= "undefined spaces" > </code><code class= "plain" >k = k - 1; </code></div><div class= "line number47 index46 alt2" ><code class= "undefined spaces" > </code><code class= "keyword" > return </code> <code class= "keyword" > true </code><code class= "plain" >; </code></div><div class= "line number48 index47 alt1" ><code class= "undefined spaces" > </code><code class= "plain" >} </code></div><div class= "line number49 index48 alt2" ><code class= "undefined spaces" > </code> </div><div class= "line number50 index49 alt1" ><code class= "undefined spaces" > </code><code class= "plain" >} </code></div><div class= "line number51 index50 alt2" ><code class= "plain" >} </code></div><div class= "line number52 index51 alt1" ><code class= "undefined spaces" > </code> </div><div class= "line number53 index52 alt2" ><code class= "plain" >let root = </code><code class= "keyword" > new </code> <code class= "plain" >Node(1) </code></div><div class= "line number54 index53 alt1" ><code class= "plain" >root.left = </code><code class= "keyword" > new </code> <code class= "plain" >Node(4) </code></div><div class= "line number55 index54 alt2" ><code class= "plain" >root.left.right = </code><code class= "keyword" > new </code> <code class= "plain" >Node(7) </code></div><div class= "line number56 index55 alt1" ><code class= "plain" >root.left.left = </code><code class= "keyword" > new </code> <code class= "plain" >Node(3) </code></div><div class= "line number57 index56 alt2" ><code class= "plain" >root.left.right.left = </code><code class= "keyword" > new </code> <code class= "plain" >Node(8) </code></div><div class= "line number58 index57 alt1" ><code class= "plain" >root.right = </code><code class= "keyword" > new </code> <code class= "plain" >Node(2) </code></div><div class= "line number59 index58 alt2" ><code class= "plain" >root.right.right = </code><code class= "keyword" > new </code> <code class= "plain" >Node(6) </code></div><div class= "line number60 index59 alt1" ><code class= "plain" >let item = 3 </code></div><div class= "line number61 index60 alt2" ><code class= "undefined spaces" > </code><code class= "plain" >let k = 1 </code></div><div class= "line number62 index61 alt1" ><code class= "undefined spaces" > </code><code class= "plain" >let loc = k </code></div><div class= "line number63 index62 alt2" ><code class= "undefined spaces" > </code><code class= "plain" >let flag = ancestor(root, item) </code></div><div class= "line number64 index63 alt1" ><code class= "undefined spaces" > </code> </div><div class= "line number65 index64 alt2" ><code class= "undefined spaces" > </code><code class= "keyword" > if </code> <code class= "plain" >(flag) </code></div><div class= "line number66 index65 alt1" ><code class= "undefined spaces" > </code><code class= "plain" >document.write(</code><code class= "string" > "Ancestor doesn't exist" </code><code class= "plain" >) </code></div><div class= "line number67 index66 alt2" ><code class= "undefined spaces" > </code><code class= "keyword" > else </code></div><div class= "line number68 index67 alt1" ><code class= "undefined spaces" > </code><code class= "plain" >document.write(</code><code class= "string" > "is the " </code> <code class= "plain" >+ (loc) + </code></div><div class= "line number69 index68 alt2" ><code class= "undefined spaces" > </code><code class= "string" > "th ancestor of [" </code> <code class= "plain" >+ (item) + </code><code class= "string" > "]" </code><code class= "plain" >) </code></div><div class= "line number70 index69 alt1" ><code class= "undefined spaces" > </code> </div><div class= "line number71 index70 alt2" ><code class= "comments" >
|
Output
[4] is the 1th ancestor of [3]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 3: Iterative Approach
The basic idea behind the iterative approach is to traverse the binary tree from the root node and keep track of the path from the root to the target node using a stack. Once we find the target node, we pop elements from the stack and add their values to a vector until we reach the kth ancestor or the stack becomes empty
Follow the Steps below to implement the above idea:
- Initialize a stack to keep track of the path from the root to the target node, and a vector to store the ancestors.
- Traverse the binary tree from the root node using a while loop.
- If the current node is not NULL, push it onto the stack and move to its left child.
- If the current node is NULL, pop the top element from the stack. If the top element is the target node, break out of the loop. Otherwise, move to its right child.
- If the target node is not found, return -1.
- Pop elements from the stack and add their values to the ancestors vector until we reach the kth ancestor or the stack becomes empty.
- If the stack becomes empty before we reach the kth ancestor, return -1.
- Return the value of the kth ancestor
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
class TreeNode {
constructor(x) {
this .val = x;
this .left = null ;
this .right = null ;
}
}
function kthAncestor(root, node, k) {
const s = [];
const ancestors = [];
let found = false ;
while (root || s.length > 0) {
if (root) {
s.push(root);
root = root.left;
}
else {
const temp = s.pop();
if (temp.val === node) {
found = true ;
break ;
}
if (temp.right) {
root = temp.right;
}
}
}
if (!found) {
return -1;
}
while (s.length > 0 && k > 0) {
const temp = s.pop();
ancestors.push(temp.val);
k--;
}
if (k > 0) {
return -1;
}
return ancestors[ancestors.length - 1];
}
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
const node = 4;
const k = 2;
const kthAncestorVal = kthAncestor(root, node, k);
console.log(`The ${k}th ancestor of node ${node} is ${kthAncestorVal}`);
|
Output
The 2th ancestor of node 4 is 1
Time Complexity: O(N) , where N is the number of nodes in the binary tree. This is because we need to traverse the entire tree in the worst case to find the target node and the ancestors.
Space Complexity: O(N) , where N is the number of nodes in the binary tree. This is because we are using a stack to keep track of the path from the root to the target node, and in the worst case, the entire path could be stored in the stack
Last Updated :
18 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...