Wednesday, January 7, 2015

Find diameter for any tree

The diameter of a tree is the maximum length of path between any vertex in a tree. The simple solution is to start from any vertex, do a DFS, find a farthest vertex from it, then from that farthest vertex, do second DFS, find the farthest vertex from it.

//here is the graph node with adjacentList representation.
//for illustration purpose, the key of each vertex is character
public static class CNode {
char c;
Set<CNode> outgoing = new HashSet<CNode>();
CNode(char i){this.c=i;}
        public int hashCode() {}
        public boolean equals(Object o){}
}



public static int diameterOfTree(CNode[] vertices){
int[] max = new int[1];
CNode[] mNode = new CNode[1];
Set<CNode> visited = new HashSet<CNode>();
//start with any vertex in the tree
dfs(vertices[0], 0, visited, max, mNode);
CNode[] maxNode = new CNode[1];
max[0] = 0;
visited = new HashSet<CNode>();
dfs(mNode[0], 0, visited, max, maxNode);
return max[0];
}

public static void dfs(CNode start, int distance, Set<CNode> visited, int[] max, CNode[] maxNode){
visited.add(start);
max[0] = Math.max(max[0], distance);
if(max[0]==distance)
   maxNode[0] = start;
for(CNode n : start.outgoing){
if(!visited.contains(n)){
dfs(n, distance+1, visited, max, maxNode);
}
}
}

10 comments:

  1. I guess in your Node.outgoing, it includes not only the children, but also the node's parent. Right?

    ReplyDelete
    Replies
    1. Actually by definition of tree: undirected graph without any simple cycle, there are not children and parent relationship in a Tree. In other words there is NO root.
      Note the binary tree or binary search data structure, the parent/children pointers are created to facilitate the operation.

      Delete
  2. In that way, this problem can be developed to find the diameter in a connected acyclic graph.

    ReplyDelete
    Replies
    1. haha, you just define a Tree, Tree is connected acyclic undirected graph.

      Delete
    2. But tree has a definition of root, right?

      Delete
  3. I like how you define the int[] max as the parameter. Before, I would always define a new class for integer! It is awesome!

    ReplyDelete
    Replies
    1. both is ok, in a coding interview, we take whatever it is simple and faster to code. In real world, we will define a new class most likely.

      Delete
  4. Besides, I notice in this code, you used CNode[] instead of HashSet

    ReplyDelete
    Replies
    1. yes, the graph is defined as list of vertex or CNode. Thinking about each node in the graph is represented by 'a', 'b', 'c'. Then we can define out graph as:
      CNode[] graph = new CNode[26].
      graph[0] = new CNode('a');
      graph[1] = new CNode('b');

      Array is simple and space efficient than list.

      Delete