3 Oct 2013

Least Common Ancestor

Problem Statement:

     Find the Least Common Ancestor for two nodes in a Binary Search Tree.

Solution:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
//----- Least Common Ancestor in a BST
 public Node LCA(Node root, Node n1, Node n2) {

  if(root==null)
   return root;

  if(root.data > n1.data && root.data > n2.data) 
   return LCA(root.left, n1, n2);

  if(root.data < n1.data && root.data < n2.data)
   return LCA(root.right , n1, n2);

  return root;
 }

1 comment:

  1. What's up friends, how is everything, and what you want to
    say on the topic of this paragraph, in my view its truly
    amazing designed for me.

    Also visit my site smash bandits hack

    ReplyDelete