From d93492b2d8522a1489e2dda07f2e70aef3643e67 Mon Sep 17 00:00:00 2001 From: Dhruv Panwar <60705641+dhruvinfo28@users.noreply.github.com> Date: Thu, 7 Oct 2021 23:55:00 +0530 Subject: [PATCH] Add Lowest Common Ancestor of two vertices in a tree (#2380) --- DataStructures/Trees/LCA.java | 107 ++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 DataStructures/Trees/LCA.java diff --git a/DataStructures/Trees/LCA.java b/DataStructures/Trees/LCA.java new file mode 100644 index 00000000..0f3d63de --- /dev/null +++ b/DataStructures/Trees/LCA.java @@ -0,0 +1,107 @@ +package Trees; + +import java.util.ArrayList; +import java.util.Scanner; + +public class LCA { + private static Scanner scanner = new Scanner(System.in); + public static void main(String[] args){ + + //The adjacency list representation of a tree: + ArrayList> adj = new ArrayList<>(); + + //v is the number of vertices and e is the number of edges + int v = scanner.nextInt(), e = v-1; + + for(int i=0;i()); + } + + //Storing the given tree as an adjacency list + int to, from; + for(int i=0;i> adj, int s, int p, int[] parent, int[] depth){ + for(int adjacent: adj.get(s)){ + if(adjacent!=p){ + parent[adjacent] = s; + depth[adjacent] = 1 + depth[s]; + dfs(adj,adjacent,s,parent,depth); + } + } + } + + /** + * Method to calculate Lowest Common Ancestor + * @param v1 The first vertex + * @param v2 The second vertex + * @param depth An array with depths of all vertices + * @param parent An array with parents of all vertices + * @return Returns a vertex that is LCA of v1 and v2 + */ + private static int getLCA(int v1, int v2, int[] depth, int[] parent){ + if(depth[v1] < depth[v2]){ + int temp = v1; + v1 = v2; + v2 = temp; + } + while(depth[v1]!=depth[v2]){ + v1 = parent[v1]; + } + if(v1==v2) return v1; + while(v1!=v2){ + v1 = parent[v1]; + v2 = parent[v2]; + } + return v1; + } +} + +/** + * Input: + * 10 + * 0 1 + * 0 2 + * 1 5 + * 5 6 + * 2 4 + * 2 3 + * 3 7 + * 7 9 + * 7 8 + * 9 4 + * Output: + * 2 + */ \ No newline at end of file