Challenge 3: Finding Ancestors of a Given Node in a BST
If you are given the root to a binary search tree and a node value k, can you write a code to find the ancestor of that node?
We'll cover the following
Problem statement
Implement the string findAncestors(Node *rootNode, int k)
function, which will find the ancestors of the node whose value is “k.”. Here rootNode
is the root node of a binary search tree, and k
is an integer value of the node whose ancestors you need to find. An illustration is also given below. Your code is evaluated on the tree given in the example.
Input
This is the root node and a number k
.
Output
It returns all the ancestors of k
in the binary search tree in a string separated by a comma.
Sample input
bst = {
6 -> 4,9
4 -> 2,5
9 -> 8,12
12 -> 10,14
}
where parent -> leftChild,rightChild
k = 10
Sample output
12,9,6,
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.