2016-07-07

Binary Search Tree : Lowest Common Ancestor


  1.  /* Node is defined as :
  2.  class Node 
  3.     int data;
  4.     Node left;
  5.     Node right;
  6.     
  7.     */

  8. static Node lca(Node root,int v1,int v2)
  9.     {

  10.        //Decide if you have to call rekursively
  11.     //Samller than both
  12.     if(root.data < v1 && root.data < v2){
  13.         return lca(root.right,v1,v2);
  14.     }
  15.     //Bigger than both
  16.     if(root.data > v1 && root.data > v2){
  17.         return lca(root.left,v1,v2);
  18.     }

  19.     //Else solution already found
  20.     return root;
  21.     }


No comments:

Post a Comment