- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to find Kth ancestor of a tree node in Python

Suppose we have a tree with n nodes that are numbered from 0 to n-1. The tree is given by a parent array, where parent[i] is the parent of node i. The root of the tree is node 0. We have to find the kth ancestor of a given node, if the ancestor is not present, then return -1

So, if the input is like

then the output will be 2 because the first ancestor of node 6 is 5 and the second is 2.

To solve this, we will follow these steps −

Define a function solve() . This will take parent, node, k

if node is same as -1, then

return -1

otherwise when k is same as 1, then

return parent[node]

otherwise when (k AND k-1) is zero, then

return solve(parent, solve(parent, node, quotient of k/2) , quotient of k/2)

otherwise,

msb := 2^(number of bits of k -1)

return solve(parent, solve(parent, node, k-msb) , msb)

## Example

Let us see the following implementation to get better understanding

def solve(parent, node, k): if node == -1: return -1 elif k == 1: return parent[node] elif not (k & k-1): return solve(parent, solve(parent, node, k >> 1), k >> 1) else: msb = 1 << (k.bit_length()-1) return solve(parent, solve(parent, node, k-msb), msb) parent = [-1,0,0,1,2,2,5,5] node = 6 k = 2 print(solve(parent, node, k))

## Input

[6,7,9,16,22], 2

## Output

2

- Related Articles
- Program to find leftmost deepest node of a tree in Python
- Program to find out the lowest common ancestor of a binary tree using Python
- Program to find sibling value of a binary tree node in Python
- Find the kth node in vertical order traversal of a Binary Tree in C++
- Program to find an ancestor which is common of two elements in a binary tree in Python
- Python Program to Find Nth Node in the Inorder Traversal of a Tree
- Kth node in Diagonal Traversal of Binary Tree in C++
- C++ Program to Find Lowest Common Ancestor in a Binary Search Tree
- Program to find the kth smallest element in a Binary Search Tree in Python
- Program to find second deepest node in a binary tree in python
- Program to find out the lowest common ancestor of a binary tree of given nodes using Python
- Program to find out the lowest common ancestor of a binary tree using parent pointers using Python
- Lowest Common Ancestor of a Binary Tree in Python
- Find the Kth node in the DFS traversal of a given subtree in a Tree in C++
- Golang Program to insert a new node after the Kth node.