I am trying to make a program to find the distance between two nodes, given parent to child relation
Input
1 2
1 3
3 4
3 5
I have used following code to get the values. The tree is bidirectional and has unit distance from each node.
Code
Map<Integer, List<Integer>> adjacencies = new HashMap<Integer, List<Integer>>();
for (int i=1; i<=n; i++) {
List<Integer> l1= new ArrayList<Integer>();
adjacencies.put(i,l1);
}
for (int i=0; i<n-1; i++) {
int u = in.nextInt();
int v = in.nextInt();
adjacencies.get(u).add(v);
adjacencies.get(v).add(u);
}