Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to find distance between 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 {
- static int level_of_node(node root, int data){
- return level_of_node_helper(root, data, -1);
- }
- // function to find and return the level of a node in binary tree
- static int level_of_node_helper(node root, int data, int level){
- // if the tree is isEmpty or if we reach a leaf node then return 0
- if (root == null){
- return -1;
- }
- if(root.data == data){
- return level+1;
- }
- // check in the left subtree for the element
- // if found then return the level
- int level_node = level_of_node_helper(root.left, data, level + 1);
- if (level_node != -1){
- return level_node;
- }
- // searching for the node in right subtree
- level_node = level_of_node_helper(root.right, data, level + 1);
- return level_node;
- }
- // 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);
- }
- // function that returns the distance between 2 given nodes
- static int distance_between(node root, int a, int b){
- node LCA = least_common_ancestor(root, a, b);
- return level_of_node(LCA, a) + level_of_node(LCA, b);
- }
- 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("Distance between nodes 6 and 10 is : " + distance_between(head, 6, 10));
- System.out.println("Distance between nodes 1 and 10 is : " + distance_between(head, 1, 10));
- System.out.println("Distance between nodes 11 and 10 is : " + distance_between(head, 11, 10));
- }
- }
Add Comment
Please, Sign In to add comment