I have solved the problem with only if statements. It can be solved in various other ways. I have just started programming, so I could not think of using any other data structure for solving this.
My QUESTION :
How to choose the best approach among various ways? And what are the advantages/disadvantages of this best approach compared to my direct naive approach.
Not only for this problem, in general. How to arrive at the possible approach for any problem?
Problem Statement
You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. You only need to complete the function.
My code:
static Node lca(Node root,int v1,int v2)
{
Node r = root;
if( r == null){
return null;
}
else if(r.data == v1 || r.data == v2){
return r;
}
else if(r.data > v1 && r.data < v2){
return r;
}
else if(r.data > v2 && r.data < v1){
return r;
}
else if( r.data > v1 && r.data > v2){
lca(r.left, v1, v2);
}
else if( r.data < v1 && r.data < v2){
lca(r.right, v1, v2);
}
return null;
}
Problem link: https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-ancestor
return
s missing fromlca(r.left...)
andlca(r.right...)
, the solution seems to be correct. As you correctly identified, the LCA will be the number that is greater thanv1
but less thanv2
(or vice versa). – biziclop