//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);
}
}
}
I guess in your Node.outgoing, it includes not only the children, but also the node's parent. Right?
ReplyDeleteActually 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.
DeleteNote the binary tree or binary search data structure, the parent/children pointers are created to facilitate the operation.
In that way, this problem can be developed to find the diameter in a connected acyclic graph.
ReplyDeletehaha, you just define a Tree, Tree is connected acyclic undirected graph.
DeleteBut tree has a definition of root, right?
DeleteI like how you define the int[] max as the parameter. Before, I would always define a new class for integer! It is awesome!
ReplyDeleteboth 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.
DeleteBesides, I notice in this code, you used CNode[] instead of HashSet
ReplyDeleteHashSet
Deleteyes, 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:
DeleteCNode[] graph = new CNode[26].
graph[0] = new CNode('a');
graph[1] = new CNode('b');
Array is simple and space efficient than list.