List Representation: Adjacency List – N Rows of the Adjacency Matrix Are
Total Page:16
File Type:pdf, Size:1020Kb
List Representation: Adjacency List { n rows of the adjacency matrix are repre- sented as n linked lists { Declare an Array of size n e.g. A[1:::n] of Lists { A[i] is a pointer to the edges in E(G) starting at vertex i. Undirected graph: data in each list cell is a number indicating the adjacent vertex Weighted graph: data in each list cell is a pair (vertex, weight) 1 a b c e a [b,2] [c,6] [e,4] b a b [a,2] c a e d c [a,6] [e,3] [d,1] d c d [c,1] e a c e [a,4] [c,3] Properties: { the degree of any node is the number of elements in the list { O(e) to check for adjacency for e edges. { O(n + e) space for graph with n vertices and e edges. 2 Search and Traversal Techniques Trees and Graphs are models on which algo- rithmic solutions for many problems are con- structed. Traversal: All nodes of a tree/graph are exam- ined/evaluated, e.g. | Evaluate an expression | Locate all the neighbours of a vertex V in a graph Search: only a subset of vertices(nodes) are examined, e.g. | Find the first token of a certain value in an Abstract Syntax Tree. 3 Types of Traversals Binary Tree traversals: | Inorder, Postorder, Preorder General Tree traversals: | With many children at each node Graph Traversals: | With Trees as a special case of a graph 4 Binary Tree Traversal Recall a Binary tree | is a tree structure in which there can be at most two children for each parent | A single node is the root | The nodes without children are leaves | A parent can have a left child (subtree) and a right child (subtree) A node may be a record of information | A node is visited when it is considered in the traversal | Visiting a node may involve computation with one or more of the data fields at the node. 5 In-Order, process in between the two subtrees. Algorithm Inorder(T ree T )f if Not IsEmpty(T )f Inorder(Lchild(T )); P rocess(Data(T )); Inorder(Rchild(T )); g g Preorder, process before anything else. Algorithm P reorder(T ree T )f if Not IsEmpty(T )f P rocess(Data(T )); P reorder(Lchild(T )); P reorder(Rchild(T )); g g Postorder, process after anything else. Algorithm P ostorder(T ree T )f if Not IsEmpty(T )f P ostorder(Lchild(T )); P ostorder(Rchild(T )); P rocess(Data(T )); g g 6 7 Example: Print out the nodes. Inorder: Preorder: Postorder: 8.