Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to print the least common ancestor of 2 nodes in a given binary tree
- /**
- * Created by MOHIT on 25-05-2018.
- */
- import java.io.*;
- import java.lang.reflect.Array;
- import java.util.*;
- import static java.lang.Integer.max;
- // node class
- class node{
- int data;
- node left;
- node right;
- // function that returns a pointer to new node
- public node(int element){
- this.data = element;
- this.left = null;
- this.right = null;
- }
- };
- public class BinaryTree {
- // function to find the least common ancestor of 2 nodes in a binary tree
- static node least_common_ancestor(node root, int n1, int n2){
- if(root == null){
- return root;
- }
- if(root.data == n1 || root.data == n2){
- return root;
- }
- node left = least_common_ancestor(root.left, n1, n2);
- node right = least_common_ancestor(root.right, n1, n2);
- if(left != null && right != null){
- return root;
- }
- if(left != null){
- return least_common_ancestor(root.left, n1, n2);
- }
- return least_common_ancestor(root.right, n1, n2);
- }
- public static void main(String arg[]) {
- node head = new node(1);
- head.left = new node(2);
- head.right = new node(3);
- head.left.left = new node(4);
- head.left.right = new node(5);
- head.right.right = new node(6);
- head.left.left.right = new node(7);
- head.right.right.left = new node(8);
- head.left.left.right.left = new node(9);
- head.left.left.right.left.left = new node(10);
- head.right.right.left.right = new node(11);
- System.out.println("Least common Ancestor of nodes 6 and 10 is : " + least_common_ancestor(head, 6, 10).data);
- System.out.println("Least common Ancestor of nodes 4 and 5 is : " + least_common_ancestor(head, 4, 5).data);
- System.out.println("Least common Ancestor of nodes 5 and 10 is : " + least_common_ancestor(head, 5, 10).data);
- }
- }
Add Comment
Please, Sign In to add comment