m2skills

LCA java

Jun 1st, 2018
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.13 KB | None | 0 0
  1. // http://code2begin.blogspot.com
  2. // program to print the least common ancestor of 2 nodes in a given binary tree
  3.  
  4. /**
  5.  * Created by MOHIT on 25-05-2018.
  6.  */
  7.  
  8. import java.io.*;
  9. import java.lang.reflect.Array;
  10. import java.util.*;
  11.  
  12. import static java.lang.Integer.max;
  13.  
  14.  
  15. // node class
  16. class node{
  17.     int data;
  18.     node left;
  19.     node right;
  20.  
  21.     // function that returns a pointer to new node
  22.     public node(int element){
  23.         this.data = element;
  24.         this.left = null;
  25.         this.right = null;
  26.        
  27.     }
  28. };
  29.  
  30.  
  31. public class BinaryTree {
  32.  
  33.     // function to find the least common ancestor of 2 nodes in a binary tree
  34.     static node least_common_ancestor(node root, int n1, int n2){
  35.         if(root == null){
  36.             return root;
  37.         }
  38.        
  39.         if(root.data == n1 || root.data == n2){
  40.             return root;
  41.         }
  42.        
  43.         node left = least_common_ancestor(root.left, n1, n2);
  44.         node right = least_common_ancestor(root.right, n1, n2);
  45.        
  46.         if(left != null && right != null){
  47.             return root;
  48.         }
  49.        
  50.         if(left != null){
  51.             return least_common_ancestor(root.left, n1, n2);
  52.         }
  53.         return least_common_ancestor(root.right, n1, n2);
  54.     }
  55.    
  56.     public static void main(String arg[]) {
  57.         node head = new node(1);
  58.         head.left = new node(2);
  59.         head.right = new node(3);
  60.         head.left.left = new node(4);
  61.         head.left.right = new node(5);
  62.         head.right.right = new node(6);
  63.         head.left.left.right = new node(7);
  64.         head.right.right.left = new node(8);
  65.         head.left.left.right.left = new node(9);
  66.         head.left.left.right.left.left = new node(10);
  67.         head.right.right.left.right = new node(11);
  68.         System.out.println("Least common Ancestor of nodes 6 and 10 is : " + least_common_ancestor(head, 6, 10).data);
  69.         System.out.println("Least common Ancestor of nodes 4 and 5 is : " + least_common_ancestor(head, 4, 5).data);
  70.         System.out.println("Least common Ancestor of nodes 5 and 10 is : " + least_common_ancestor(head, 5, 10).data);
  71.     }
  72. }
Add Comment
Please, Sign In to add comment