VOOZH about

URL: https://www.geeksforgeeks.org/dsa/kth-ancestor-node-binary-tree/

⇱ K-th Ancestor in a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

K-th Ancestor in a Binary Tree

Last Updated : 29 Apr, 2026

Given a binary tree of size n, along with a node and a positive integer k, find the k-th ancestor of the given node in the binary tree. If such an ancestor does not exist, return -1.

Note: It is guaranteed that the node exists in the tree and all the nodes of the tree have distinct values.

Examples:

Input: k = 2, node = 4

πŸ‘ blobid0_1745302099

Output: 1
Explanation: Since, k is 2 and node is 4, so we first need to locate the node and look k times its ancestors. In this case, node 4 has 1 as its 2nd ancestor, which is the root of the tree.

Input: k=1, node=3
πŸ‘ Image
Output: 1
Explanation: k = 1 and node = 3, k-th ancestor of node 3 is 1.

Using Hash Map & Level Order Traversal - O(n) Time and O(n) Space

This idea is to find the k-th ancestor by first storing the parent of every node in a map using level order traversal (BFS). Once we know each node’s direct parent, we can easily move upward from the given node step-by-step. By repeating this process k times (or until the root is reached), we reach the required k-th ancestor efficiently.

Once the parent map is built, the k-th ancestor can be found as:

  • 1st ancestor = parent[i]
  • 2nd ancestor = parent[parent[i]]
  • 3rd ancestor = parent[parent[parent[i]]]
  • …
  • k-th ancestor = applying parent[] k times on node i

Consider the tree given below:

πŸ‘ blobid0_1745302099
  1. Perform BFS and store each node’s parent:
    parent[1] = -1, parent[2] = 1, parent[3] = 1, parent[4] = 2, parent[5] = 2.
  2. Start from given node = 4 with k = 2.
  3. First move: go to parent from 4 to 2, now k = 1.
  4. Second move: go to parent from 2 to 1, now k = 0.
  5. When k becomes 0, current node 1 is the k-th ancestor.

Output
1

Using Recursive Backtracking - O(n) Time and O(n) Space

The idea is to traverse the tree using recursion to first locate the target node and then trace back toward the root. During this backtracking phase, we decrease the value of k at each step as we move up through its ancestors. When k becomes 0, the current node at that point is the k-th ancestor.

Consider the tree given below:

πŸ‘ frame_3207
  1. First, check if k == 0. If yes, return the current node as the ancestor; otherwise, move one level up and reduce k by 1.
  2. Initially, k = 2. Start searching for node 8.
  3. At node 8: k != 0 (k = 2), so reduce k = 1 and move up to its parent 7.
  4. At node 7: k != 0 (k = 1), so reduce k = 0 and move up to its parent 4.
  5. At node 4: now k == 0, so return 4 as the k-th ancestor.

Output
1
Comment
Article Tags:
Article Tags: