Welcome to an exciting lesson on Data Structures and Algorithms! Today, we'll dive into a common problem faced during tree traversals - finding the Kth ancestor of a node in a binary tree.
A binary tree is a data structure that consists of nodes, where each node has at most two children, referred to as the left child and the right child. The node without any children is called a leaf node.
Given a binary tree and an integer k, find the kth ancestor of a given node in the tree. An ancestor of a node is any node on the path from the node to the root of the tree.
k, we have found the kth ancestor.k, we have gone past the required ancestor and can stop the traversal.Let's write a recursive function to find the Kth ancestor in a binary tree. Here's a simple example in Python:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.key = key
def kthAncestor(root, k, node, ancestor=None):
if not root:
return ancestor
# If root is the node itself
if root.key == node:
return root
# Move to the left or right child depending on the count
if k <= ancestor is None:
return kthAncestor(root.left, k, node, root.key) if root.left else kthAncestor(root.right, k, node, root.key)
# Move to the left or right child based on ancestor's count
k -= ancestor + 1
return kthAncestor(root.left, k, node, root.left.key) if k >= 0 else kthAncestor(root.right, k, node, root.right.key)
# Test the function with the following binary tree:
# 1
# / \
# 2 3
# / \
# 4 5
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.right.right = Node(5)
node = 4 # The given node
k = 2 # The required depth
print(kthAncestor(root, k, node).key) # Output: 2The Kth ancestor problem is crucial in various real-world scenarios, such as:
What does a binary tree consist of?
What is the Kth ancestor of a node in a binary tree?