26. Kth Ancestor in a Tree
The problem can be found at the following link: Question Link
My Approach
To find the Kth ancestor of a node in a binary tree, I use a recursive function called
findAncestor
. This function traverses the tree while keeping track of the distance from the target node to the current node.When we find the target node, we return
k-1
as the remaining distance towards its ancestor. During the backtracking process, the function continuously updates the minimum distance encountered so farnewK
in the left and right subtrees.Once
newK
becomes zero, it indicates that we have reached the Kth ancestor. At this point, the data of the current node is stored in the variableout
, which serves as our required output."
Time and Auxiliary Space Complexity
Time Complexity:
O(N)
, whereN
is the number of nodes in the binary tree. In the worst case, we may have to visit all nodes to find the Kth ancestor.Auxiliary Space Complexity:
O(H)
, whereH
is the height of the binary tree. This space is used for the recursive call stack during the traversal.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated