1

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?

hbak
  • 1,313
  • 2
  • 9
  • 20
  • The naming convention you've picked makes this algorithm hard to follow, any chance you could label the nodes you're using a bit better? Also, a bit more indentation would also make this easier to read. – Lasse V. Karlsen Dec 10 '18 at 21:22
  • @LasseVågsætherKarlsen Hope it's better now – hbak Dec 10 '18 at 21:30
  • You should not use Exceptions for flow control. That said, the one error case here is when one or both of the nodes aren't even present in the tree and that may warrant an Exception, but certainly not for the 'found' case. BUT first, why are you returning bool values and not the common node asked for? – Ian Mercer Dec 10 '18 at 22:08
  • And as for a better algorithm, there are plenty on Stack Overflow. See for example: https://stackoverflow.com/questions/1484473/how-to-find-the-lowest-common-ancestor-of-two-nodes-in-any-binary-tree?r=SearchResults – Ian Mercer Dec 10 '18 at 22:10
  • @IanMercer you're right about the error case. I found a solution similar to mine in the link you provide. However, I believe my code will terminate the algorithm if the common ancestor is found. I mean it is not going to search through the whole network. – hbak Dec 11 '18 at 03:05

0 Answers0