Graph Data Structure

Definition

Graph node for a directed graph

class DirectedGraphNode {
    int label;
    List<DirectedGraphNode> neighbors;    
    GraphNode(int val) {
        label = val;
        neighbors = new ArrayList<DirectedGraphNode>();
    }
}

Graph node for an undirected graph

class UndirectedGraphNode {
    int label;
    List<UndirectedGraphNode> neighbors;    
    GraphNode(int val) {
        label = val;
        neighbors = new ArrayList<UndirectedGraphNode>();
    }
}

We can use the same graph node for an undirected graph. But when adding an edge, we have to add it in both directions since it is bidirectional.

Last updated