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 to solve it on your own first.
We'll cover the following
Problem Statement
Implement the find_ancestors(root, k)
function which will find the ancestors of the node whose value is “k”. Here root
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 tree in a Python list.
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 70+ hands-on prep courses.