Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
- import java.util.Scanner;
- public class Main
- {
- private static class Node
- {
- private Node left;
- private Node right;
- private int value;
- public Node(int value)
- {
- this.value = value;
- }
- public String toString()
- {
- return " Value: " + value + "\n";
- }
- }
- private static void insert(int value, Node root)
- {
- if( value < root.value )
- {
- if( root.left != null )
- {
- insert(value,root.left);
- }
- else
- {
- root.left = new Node(value);
- }
- }
- else
- {
- if( root.right != null )
- {
- insert(value,root.right);
- }
- else
- {
- root.right = new Node(value);
- }
- }
- }
- private static Node populate(int[] values, int n)
- {
- if( n <= 0 )
- {
- return null;
- }
- Node root = new Node(values[0]);
- for( int i =1 ; i < n ; i ++ )
- {
- insert(values[i],root);
- }
- return root;
- }
- public static void main(String[] args) {
- Main man = new Main();
- }
- public static int bstDistance(int[] values, int n, int node1, int node2) {
- Node node = populate(values,n);
- return findDistance(node,node1,node2);
- }
- public static int findDistance(Node root, int n1, int n2) {
- int x = Pathlength(root, n1) - 1;
- int y = Pathlength(root, n2) - 1;
- if( x < 0 || y < 0 )
- {
- return -1;
- }
- int lcaData = findLCA(root, n1, n2).value;
- int lcaDistance = Pathlength(root, lcaData) - 1;
- return (x + y) - 2 * lcaDistance;
- }
- public static int Pathlength(Node root, int n1) {
- if (root != null) {
- int x = 0;
- if ((root.value == n1) || (x = Pathlength(root.left, n1)) > 0
- || (x = Pathlength(root.right, n1)) > 0) {
- // System.out.println(root.value);
- return x + 1;
- }
- return -1;
- }
- return -1;
- }
- public static Node findLCA(Node root, int n1, int n2) {
- if (root != null) {
- if (root.value == n1 || root.value == n2) {
- return root;
- }
- Node left = findLCA(root.left, n1, n2);
- Node right = findLCA(root.right, n1, n2);
- if (left != null && right != null) {
- return root;
- }
- if (left != null) {
- return left;
- }
- if (right != null) {
- return right;
- }
- }
- return null;
- }
- private void print(Node tree)
- {
- System.out.print(tree);
- System.out.print("left" + tree.left + "");
- System.out.print("right" + tree.right + "");
- if( tree.left != null )
- {
- print(tree.left);
- }
- if( tree.right != null )
- {
- print(tree.right);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement