I am working on this exercise from Hackerrank(https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-ancestor/copy-from/158548633)
In this exercise, we are given a pointer to the root of the binary search tree and two values v1
and v2
. We need to return the lowest common ancestor (LCA) of v1
and v2
in the binary search tree. we have to complete the function lca
. It should return a pointer to the lowest common ancestor node of the two values given.
lca has the following parameters:
root: a pointer to the root node of a binary search tree
v1: a node.data value
- v2: a node.data value
I know the recursive solution is easier but I tried this approach and couldn't find any reason for failing test cases. The below-mentioned solution passes only 6/10 test cases. I can't see all the 4 failed test cases but I can mention 1 test case.
here's my code
/*The tree node has data, left child and right child
class Node {
int data;
Node* left;
Node* right;
};
*/
vector<Node*> find(int v, Node* root)
{
vector<Node*> ar;
if (v == root->data) {
ar.push_back(root);
return ar;
}
if (v > root->data) {
ar.push_back(root);
find(v, root->right);
}
if (v < root->data) {
ar.push_back(root);
find(v, root->left);
}
ar.push_back(root);
return ar;
}
Node* lca(Node* root, int v1, int v2)
{
//this vector contains the nodes in path
//to reach from root to node
vector<Node *> a, b;
//find function return the vector
a = find(v1, root);
b = find(v2, root);
//index of the LCA in the vector
int res = 0;
//traversing the two vectors from
//beg to end if two nodes are same
//update the value of res. Final updated
//value will give us LCA
int n = b.size();
if (a.size() < b.size())
n = a.size();
int i = 0;
while (i < n) {
if (a[i] == b[i])
res = i;
i++;
}
return a[res];
}
failed test case:
8
8 4 9 1 2 3 6 5
1 2
Expected output:
1
My output:
8
needed help to debug the code and to find the loophole in this approach.