Adjacency lists and their similar structures
One of the most intuitive ways to implement a graph structure is to use adjacency lists. Let's implement one of the simplest: suppose now we have n nodes, numbered 0,...,n-1 respectively.
Then, each adjacency list is a list of numbers, and we can put them into a master list of size n and index them with the node number.
  
Adjacency Set notation:
A, B, C, D, E, F, g, H = range (8) N = [{b, C, D, E, F}, #        a {c, e}, # b {d}, #                 C {e}, #                    d {f}, #                    e {c, G, H},              # f {f, H},                 # g {F, G}                  
Adjacency List
A, B, C, D, E, F, g, H = range (8) N = [[B, C, D, E, F],        # A [C, E], #                 b [D], # C [E], #                    D [F], #                    E [C, G, H],              # f [F, H],                 # G [F, G]                  
Weighted adjacency Dictionary
A, B, C, D, E, F, g, H = range (8) N = [{b:2, c:1, D:3, E:9, F:4}, #   a {c:4, e:3}, # b {d:8}, #                       C {e:7                       }, # d {F:5},                       # e {c:2, g:2, h:2},             # f {f:1, h:6},                  # g {f:9, g:8}                   # H]
Adjacency Matrix
Adjacency matrix of nested list implementations
A, B, C, D, E, F, g, H = Range (8) # a B c d e f g HN = [[0,1,1,1,1,1,0,0], # a     [0,0,1,0,1,0,0,0], # b     [0,0,0,1,0,0, 0,0], # c     [0,0,0,0,1,0,0,0], # D     [0,0,0,0,0,1,0,0], # e     [0,0,1,0,0,0,1,1], # f     [0,0,0,0,0,1,0,1], # G     
Since there is no self-looping state on the graph, the values on the diagonal should be all false.
The adjacency matrix of a non-graph should be a symmetric matrix.
We usually set the weight of the non-existent edge to infinity.
inf = float (' inf ')
A, B, C, D, E, F, g, H = Range (8) # a B c d e f g hN = [[INF, 1, 1, 1, 1, 1, Inf,inf], # a     [Inf,inf, 1, INF, 1, INF , Inf,inf], # b     [Inf,inf,inf, 1, Inf,inf,inf,inf], # c     [Inf,inf,inf,inf, 1, Inf,inf,inf], # D     [Inf,inf,inf, Inf,inf, 1, Inf,inf], # e     [Inf,inf, 1, Inf,inf,inf, 1, 1], # f     [Inf,inf,inf,inf,inf, 1, INF, 1], # g     
In the adjacency matrix, the time required for the query to change (u,v) is θ (1), and the operation time of the Traverse v neighbor is θ (n);
In the adjacency list, the time required for both operations is θ (d (v))
We should choose the relevant representation according to the specific use of the graph.
The implementation of the tree
  
The tree is represented as a two-dimensional list
Binary Tree class:
  
Multi-Path Search tree class:
Class Tree:    def __init__ (self, Kids, Next=none):    self.kids = Self.val = Kids    self.next = Next    >>& Gt T = Tree ("A", Tree ("B", Tree ("C", Tree ("D")))) >>> T.kids.next.next.val ' C '
Bunch mode:
Class Bunch (Dict):    def __init__ (self, *args, **kwds):    super (Bunch, self). __init__ (*args, **kwds)    
  
The implementation of the "Python algorithm" graph and the tree