1

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);
        }
1
  • 1
    If you have a tree I'd use a tree datastructure for tree operations. Makes thinks easier to understand and code. You could use a map to directly access tree nodes by their id though. Commented Sep 18, 2015 at 11:00

4 Answers 4

2

You can use BFS to find the distance between two nodes. I hope this solution will help you.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;

public class StackOverFlow {
static Map<Integer, List<Integer>> adjacencies = new HashMap<Integer, List<Integer>>(); 

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    int n = in.nextInt();

    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);
    }

    findingDistanceBetweenTwoNodes(1, 3);
}
static int [] parent = new int[100];
static boolean [] visited = new boolean[100];

public static void findingDistanceBetweenTwoNodes(int nodea, int nodeb){

    Queue<Integer> q = new LinkedList<Integer>();
    q.add(nodea);
    parent[nodea] = -1;
    visited[nodea] = true;
    boolean loop = true;
    while(!q.isEmpty() && loop){
        int element = q.remove();
        Integer s =null;

        while((s = getChild(element))!=null) {
            parent[s] = element;
            visited[s] = true;
            if(s == nodeb)
            {
                loop= false;
                break;
            }

            q.add(s);
        }
    }
    int x = nodeb;
    int d = 0;
    if(!loop)
     {
        while(parent[x] != -1)

     {
         d +=1;
         x = parent[x];
     }

    System.out.println("\nThe distance from node "+nodea+ " to node "+nodeb+" is "   +d);
     }
    else
        System.out.println("Can't reach node "+nodeb);
}


private static Integer getChild(int element) {
    ArrayList<Integer> childs = (ArrayList<Integer>) adjacencies.get(element);
    for (int i = 0; i < childs.size(); i++) {
        if(!visited[childs.get(i)])
        return childs.get(i);
    }
    return null;

}

}

Sign up to request clarification or add additional context in comments.

Comments

0

Assume that one node can have only one parent node.

create a TreeNode type, it can have TreeNode parent, List<TreeNode> children attributes. The root node parent is null, leaf nodes have no children

I think this tree structure makes your work easier.

Comments

0

Although not impossible, personally I think that navigating a Map as a representation of a tree is too cumbersome, the best would be a data structure as described in previous answer - one where the object has its parent and children.

Calculating a distance between them is than a question of traversing the tree while looking for certain nodes, if you have no knowledge of tree traversal you can start here https://en.wikipedia.org/wiki/Tree_traversal, but it's nothing difficult, there are just more ways to go through it.

1 Comment

is there a way to find height for the above map implementation
0

I would suggest you to do it with a simple DFS procedure since it's easier to code and doesn't require extra memory (beyond recursion stack), as long as the time complexity is acceptable:

int dfs(int u, int pu, int target, int h, Map<Integer, List<Integer>> adjacencies) {
    if (u == target) { // if target reached
      return h; // return current distance
    }
    for (int v : adjacencies.get(u)) {
      if (v != pu) { // don't go up in the tree, only down
        int d = dfs(v, u, target, h+1, adjacencies);
        if (d != -1) { // if target is in this subtree
          return d;
        }
      }
    }
    return -1; // target is not in this subtree
  }

You can use it like:

int from = 1;
int to = 5;
int dist = dfs(from, -1, to, 0, adjacencies); // use from as root of DFS

Hope it helped.

2 Comments

please check your twitter account.
please reply to my mail

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.