Posted on by Kalkicode
Code Binary Tree

Kth ancestor of a node in binary tree

In a binary tree, the Kth ancestor of a node is the node that is located K levels above the node in the tree. Specifically, if we have a binary tree with nodes numbered from 1 to N, and we are given a node with number x and a positive integer K, then the Kth ancestor of node x is the node that is K levels above x in the tree.

For example, consider the following binary tree:

      /   \
     2     3
    / \   / \
   4   5 6   7

If we are given node 5 and K=2, then the 2nd ancestor of node 5 is node 1 (i.e., the root of the tree). If K=1, then the 1st ancestor of node 5 is node 2. If K=3, then the 3rd ancestor of node 5 does not exist, since there are not enough nodes above node 5 in the tree to reach the 3rd ancestor.

Finding the Kth ancestor of a node in a binary tree is a common problem in computer science and has applications in various domains such as genealogy and network routing.

Program List


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment