26. Kth Ancestor in a Tree
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
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 far newK
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 variable out
, which serves as our required output."
Time Complexity: O(N)
, where N
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)
, where H
is the height of the binary tree. This space is used for the recursive call stack during the traversal.
For discussions, questions, or doubts related to this solution, please visit our . 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 repository.