I am trying to solve this questions:
Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.
I wrote a pseudocode for the solution below. The main idea that the common ancestor's left and right subtrees must contain the two values:
Node ans;
//These are the target values/nodes (In case of values, I am assuming the are unique, no repeated values)
Value targetValue1,targetValue2;
Boolean checkExistance(Node n, Value v, Value q){
if n == null
return false;
elif n.value == v || n.value == q
return true;
checkLeft = checkExistance(n.left,targetValue1,targetValue1);
checkRight = checkExistance(n.right,targetValue1,targetValue1);
if checkLeft == checkRight == false
return false;
elif checkLeft == checkRight == true
ans = n;
thow new Excpetion("Common Ancestor was Found");
//it contains one of the node
return true;
}
I believe the exception will unwind the stack and avoid unnecessarily recursion calls. My question is this a good practice and is there any chance to improve this solution by not using the nasty exception?