Challenge: Find 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? A solution is placed in the "solution" section for your help, but we would suggest you solve it on your own first.

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 node whose ancestors you need to find. An illustration is also given. Your code is evaluated on the tree given in the example.

Output #

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 #


Level up your interview prep. Join Educative to access 70+ hands-on prep courses.