Top Banner
Data Structures and Files Teachers’ Laboratory Manual Assignment No. 6 Title of Assignment : Construction of an expression tree from a postfix expression and performing traversals. Objective: To understand the concept of the nonlinear Data structure, Tree. To know about expression tree. To understand the use of the stack in performing different operations on the trees To study different applications of Trees. Problem Statement: Accept a postfix expression and construct an expression tree and perform recursive and non- recursive traversals. Theory: A tree structure is a way of representing the hierarchical nature of a structure in a graphical form. It is named a "tree structure" because the classic representation resembles a tree, even though the chart is generally upside down compared to an actual tree, with the "root" at the top and the "leaves" at the bottom In computer science, a binary tree is a tree data structure in which each node has at most two children. Typically the child nodes are called left and right. One common use of binary trees is binary search trees; another is binary heaps. Definitions for rooted trees Directed edge: A directed edge refers to the link from University of Pune SE [IT] (2008 Course) 1
33
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript

Data Structures and Files Teachers Laboratory Manual

Assignment No. 6 Title of Assignment : Construction of an expression tree from a postfix expression and performing traversals. Objective: To understand the concept of the nonlinear Data structure, Tree. To know about expression tree. To understand the use of the stack in performing different operations on the trees To study different applications of Trees.

Problem Statement: Accept a postfix expression and construct an expression tree and perform recursive and non- recursive traversals. Theory: A tree structure is a way of representing the hierarchical nature of a structure in a graphical form. It is named a "tree structure" because the classic representation resembles a tree, even though the chart is generally upside down compared to an actual tree, with the "root" at the top and the "leaves" at the bottom In computer science, a binary tree is a tree data structure in which each node has at most two children. Typically the child nodes are called left and right. One common use of binary trees is binary search trees; another is binary heaps. Definitions for rooted trees

Directed edge: A directed edge refers to the link from the parent to the child (the arrows in the picture of the tree). Root node: The root node of a tree is the node with no parents. There is at most one root node in a rooted tree. Root is the only node in the tree with indegree=0 Leaf: A leaf is a node that has no children. Depth: The depth of a node n is the length of the path from the root to the node. The set of all nodes at a given depth is sometimes called a level of the tree. The root node is at depth zero. Height: The height of a tree is the depth of its furthest leaf. A tree with only a University of Pune SE [IT] (2008 Course) 1

Data Structures and Files Teachers Laboratory Manual

root node has a height of zero. Siblings: are nodes that share the same parent node. If a path exists from node p to node q, where node p is closer to the root node than q, then p is an ancestor of q and q is a descendant of p. Size of a node: The size of a node is the number of descendants it has including itself. In-degree of a vertex is the number of edges arriving at that vertex. Out-degree of a vertex is the number of edges leaving that vertex.

Expression Trees: Algebraic expressions such as a/b +(c-d) e have an inherent tree-like structure. For example, figure below is a representation of the given expression. This kind of tree is called an expression tree.

Postfix notation abcd-e + Prefix notation +ab -cde

The terminal nodes (leaves) of an expression tree are the variables or constants in the expression (a, b, c, d, and e). The root and non-terminal (internal) nodes of an expression tree are the operators (+, -, , and ). Subtrees are sub expressions, with the root being an operator. Notice that the parentheses which appear in the equations do not appear in the tree. Nevertheless, the tree representation has captured the intent of the parentheses since the subtraction is lower in the tree than the multiplication. Applications: Binary Trees have many Applications: 1. Expression Conversion 2. The problems in which there are only two solutions at any stage can be solved using Binary trees. 3. Binary Search trees 4. Huffmans coding tree for Data compression University of Pune SE [IT] (2008 Course) 2

Data Structures and Files Teachers Laboratory Manual

5. Symbol table Construction 6. Syntax Analysis Algorithms: [1] Algorithm Rec_Inorder ( tree) 1. if( tree not empty) 1 Rec_Inorder (tree left subtree) 2 print (tree token) 3 Rec_Inorder (tree right subtree) 2 end if end Rec_inorder [2] Algorithm Rec_postorder ( tree) 1 if( tree not empty) 1 Rec_postorder(tree left subtree) 2 Rec_postorder(tree right subtree) 3 print (tree token) 2 end if end Rec_postorder [3] Algorithm Rec_preorder ( tree) 1 if( tree not empty) 1 print (tree token) 2 Rec_preorder(tree right subtree) 3 Rec_preorder(tree left subtree) 2 end if end Rec_preorder [4] Algorithm PostfixToTree 1. while(not the end of the expression) 2. { 3. if(the next symbol in the expression is an operand) 4. { 5. create a node for the operand ; 6. push the reference to the created node onto the stack ; 7. } 8. if(the next symbol in the expression is a binary operator) 9. { 10. create a node for the operator ; University of Pune SE [IT] (2008 Course) 3

Data Structures and Files Teachers Laboratory Manual

11. 12. 13. 14. 15. 16. 17. 18. 19.

pop from the stack a reference to an operand ; make the operand the right subtree of the operator node ; pop from the stack a reference to an operand ; make the operand the left subtree of the operator node ; push the reference to the operator node onto the stack ; } } pop from the stack and return the reference to the root node End

[5] Algorithm NonRec_preorder ( tree) 1. define a stack 2. traverse the left sub-tree and output each visited node while pushing it in on the stack until the leftmost node has been visited. 3. If the right subtree is not null, pop the stack, then visit that sub-tree. Output that visited node while pushing it on the stack. If null, pop the stack. 4. Do 2 and 3 until the stack is empty. [6] Algorithm NonRec_Inorder ( tree) 1. define a stack 2. traverse the left sub-tree and push each visited node on the stack until the leftmost node has been visited. 3. If the right sub-tree in not null, pop the stack and output it, then visit the right sub-tree and push it on the stack. If null, pop the stack and output it. 4. Do 2 and 3 until the stack is empty. [7] Algorithm NonRec_postorder ( tree)

1. define a stack 2. traverse the left sub-tree and push each visited node on the stack until the leftmost node has been visited. 3. If the right sub-tree in not null, visit the right sub-tree and push it on the stack. If null, pop the stack and output it. Do 2 and 3 until the stack is empty.

University of Pune SE [IT] (2008 Course) 4

Data Structures and Files Teachers Laboratory Manual

Conclusion: Thus we have constructed an expression tree from a postfix expression and performed different traversals.

University of Pune SE [IT] (2008 Course) 5

Data Structures and Files Teachers Laboratory Manual

Assignment No. 7 Title of Assignment : Creation of a binary search tree and performing different operations on it. Objective: To understand and implement : 1. Binary search Tree ( a type of tree) 2. Primitive operations like insert, delete, search, display 3. Other operations on it like finding: depth, mirror image, a node Problem Statement: Create a binary search tree of mnemonics from assembly language(e.g. add, mult, div, sub etc.) and perform following operations: a) Insert, b) delete, c) depth of the tree, d) search a node, e) Find its mirror image f) Print original g) mirror image level wise. Theory: Binary search tree (BST) is a binary tree data structure which has the following properties: each node has a value; a total order is defined on these values; the left subtree of a node contains only values less than the node's value; the right subtree of a node contains only values greater than or equal to the node's value.

The major advantage of binary search trees is that the related sorting algorithms and search algorithms such as in-order traversal can be very efficient. Deletion There are several cases to be considered: Deleting a leaf: Deleting a node with no children is easy, as we can simply remove it from the tree. Deleting a node with one child: Delete it and replace it with its child. Deleting a node with two children: Suppose the node to be deleted is called N. We replace the value of N with either its in-order successor (the left-most child University of Pune SE [IT] (2008 Course) 6

Data Structures and Files Teachers Laboratory Manual

of the right subtree) or the in-order predecessor (the right-most child of the left subtree). Once we find either the in-order successor or predecessor, swap it with N, and then delete it. Since both the successor and the predecessor must have fewer than two children, either one can be deleted using the previous two cases. A good implementation avoids consistently using one of these nodes, however, because this can unbalance the tree.

Algorithms: [1] Algorithm mirror(struct node* node) 1. if (node==NULL) 2. return; 3. else // do the subtrees 4. mirror(node->lchild); 5. mirror(node->rchild); // swap the pointers in this node 6. temp = node->lchild; 7. node->lchild = node->rchild; 8. node->rchild = temp; 9. End if 10. End [2] Algorithm copy(struct node * node) 1. if (node!=NULL) 2. R=copy(node->lchild); 3. S=copy(node->rchild); 4. Q=getnode(); 5. Q->lchild=R; 6. Q->rchild=S; 7. Q->data=node->data; 8. End if; 9. return(Q); 10. End. [3] Algorithm equal(struct node * S,struct node * T) 1. if(S==NULL && T==NULL) 2. ans=1; University of Pune SE [IT] (2008 Course) 7

Data Structures and Files Teachers Laboratory Manual

3. End if; 4. if(S!=NULL && T!=NULL) 5. if(S->data==T->data) 6. ans=equal(S->lchild,T->lchild); 7. if(ans) 8. ans=equal(S->rchild,T->rchild); 9. End if; 10. End if; 11. End if; 12. return(ans); 13. End. [4] Algorithm depth(struct node * node) 1. if(node==NULL) 2. return NULL; 3. End if; 4. if(node->lchild==NULL && node->rchild==NULL) 5. return(0); 6. else 7. return(max(depth(node->lchild)+1,depth(node->rchild)+1)); 8. End if; 9. End. [5] Algorithm disp_cnt_leaves(struct node* node) 1. static int count=0; 2. if (node!=NULL) 3. disp_cnt_leaves(node->lchild); 4. if(node->lchild==NULL && node->rchild==NULL) 5. printf(node->data); 6. count++; 7. End if; 8. disp_cnt_leaves(node->rchild); 9. End if; 10. return count; 11. End. [6] Algorithm Search(T, key) 1. if (!T) then 2. return NULL # key not found 3. if (key < T.data) then University of Pune SE [IT] (2008 Course) 8

Data Structures and Files Teachers Laboratory Manual

4. return Search(T->lchild, key) 5. else if (key > T.data) 6. return Search(T->rchild, key) 7. else 8. return T->data # key is equal to node key. found key This operation requires O(log n) time in the average case, but needs O(n) time in the worst-case, when the unbalanced tree resembles a linked list (degenerate tree). [7] Insert(T,value) 1. q=NULL; 2. p=T; 3. while(p!=NULL) 4. { 5. if(value==p->data) 6. return(p); 7. q=p; 8. if(value < p->data) 9. p=p->lchild; 10. else 11. p=p->rchild; 12. } 13. v=maketree(value); //creates new node with value v and returns pointer 14. if (q==NULL) 15. T=v 16. else 17. if (valuedata) 18. q->lchild=v; 19. else 20. q->rchild=v; 21. return v; [8] Delete(T,value) 1. 2. 3. 4. 5. 6. 7. 8. q=NULL; // q is father node of p p=T; while(p!=NULL) { if(value==p->data) return(p); q=p; if(value < p->data) University of Pune SE [IT] (2008 Course) 9

Data Structures and Files Teachers Laboratory Manual

9. p=p->lchild; 10. else 11. p=p->rchild; 12. } 13. id (p is NULL) 14. return; // node does not exist, tree remains unchanged 15. if(p->lchild is absent) //case 1----only rchild is present 16. rp= p->rchild //rp points to the node that replaces node p 17. else 18. if (p->rchild is absent) //case 2 ---------only lchild is present 19. rp=p->lchild 20. else //case 3--------both children present 21. { 22. f=p; //f points to father of rp 23. rp=p->rchild 24. s=rp->lchild; // s is always the left son of rp */ 25. while(s!=NULL) 26. { 27. f=rp; 28. rp=s; 29. s=rp->lchild; 30. } // now rp points to the inorder successor of p 31. if (f not equal to p) 32. { 33. f->lchild=rp->rchild // p is not father of rp and rp==f->left 34. rp->rchild = p->rchild; 35. } 36. rp->lchild=p->lchild; 37. } 38. if( q is NULL) 39. T=rp; 40. else 41. { 42. if(p==q->lchild) 43. q->left=rp 44. else 45. q->rchild=rp; 46. } 47. freenode(p); 48. return;

University of Pune SE [IT] (2008 Course) 10

Data Structures and Files Teachers Laboratory Manual

Analysis: Best-case running time Printing takes O(n) time and n insertion cost O(lg n) each (tree is balanced, half the insertions are at depth lg(n) -1). This gives the best-case running time O(n lg n). Worst-case running time Printing still takes O(n) time and n insertion costing O(n) each (tree is a single chain of nodes) is O(n2). The n insertion cost 1, 2, 3, . . . n, which is arithmetic sequence so it is n2/2. Conclusion: Thus we have constructed a binary search tree and performed different operations like: Finding its mirror image, Printing original and mirror image level wise, Finding height & printing leaf nodes and count of leaves, Checking equality of trees and copying tree has been implemented.

University of Pune SE [IT] (2008 Course) 11

Data Structures and Files Teachers Laboratory Manual

Assignment No. 8 Title of Assignment : Representation of a given graph using adjacency list and performing DFS and BFS Problem Statement: Represent a given graph using adjacency list and perform DFS and BFS. Use the map of the area around the college as the graph. Identify the prominent land marks as nodes and perform DFS and BFS on that. Theory : Graph Traversal Methods: 1. Depth First Search It visits all of the vertices in a graph by processing a vertex and all of its descendants before processing an adjacent vertex. In this method we go deep down. When there are no adjacent non visited nodes then we proceed backwards. We make use of Stack data structure as it has the LIFO property. 2. Breadth First Search It visits all of the vertices in a graph by processing a vertex and all of its adjacent vertices. In this method we pick a node to visit first and place its unprocessed adjacent nodes in the queue. We make use of Queue data structure as it has the FIFO property. Applications: DFS 1. 2. 3. 4. 5. Finding connected components. Topological sorting. Finding 2-(edge or vertex)-connected components. Finding strongly connected components. Solving puzzles with only one solution, such as mazes. (DFS can be adapted to find all solutions to a maze by only including nodes on the current path in the visited set.)

BFS 1. Finding all nodes within one connected component University of Pune SE [IT] (2008 Course) 12

Data Structures and Files Teachers Laboratory Manual

2. Finding the shortest path between two nodes u and v (in an weighted & unweighted graph) 3. Testing a graph for bipartiteness 4. (Reverse) CuthillMcKee mesh numbering Algorithms: [I] Algorithm for Creation of Adjacency list 1. Declare an array of pointers to a link list having a data field (to store vertex number) and a forward pointer. The number of elements in the array of pointers would equal the total number of vertices in the graph. 2. Take the edge set from the user. If for example, vertex 1 is connected to vertex 2 and 3 in the graph, the 1st location of the array of pointers (corresponding to vertex 1) would point to 2 nodes, one having the data 2 (corresponding to vertex 2) and the other having data 3. 3. In this way construct the entire adjacency list.

[II] Algorithm for Depth First Search traversal 1. Select any node in the graph. Mark this node as visited, push this node onto the stack 2. Find the adjacent node to the node on the top of the stack, and which is not yet visited, (We can use the adjacency list/ matrix for it). Make this new node as visited and push onto the stack. 3. Repeat step 2, until no new adjacent node to the top of the stack can be found. When no new adjacent node can be found, pop the top of the stack. 4. Repeat step 2 and 3 until stack becomes empty 5. Repeat above steps if there are any more nodes which are still unvisited. 6. Stop. University of Pune SE [IT] (2008 Course) 13

Data Structures and Files Teachers Laboratory Manual

[III] Algorithm for Breadth First Search traversal Read the node from which you want to traverse the graph say V[i] Initialise the visited array to 1 at the index i. Insert the visited vertex V[i] in the queue. Visit the vertex which is at the front of the queue. Delete it from the queue and place its adjacent nodes in the queue 5. Repeat step 4, until the queue is not empty. 6. Stop. Analysis: DFS The time and space analysis of DFS differs according to its application area. In theoretical computer science, DFS is typically used to traverse an entire graph, and takes time O(|V| + |E|), linear in the size of the graph. In these applications it also uses space O(|V|) in the worst case to store the stack of vertices on the current search path as well as the set of already-visited vertices. Thus, in this setting, the time and space bounds are the same as for breadth first search and the choice of which of these two algorithms to use depends less on their complexity and more on the different properties of the vertex orderings the two algorithms produce. Time Complexity O ( | V | + | E | ) for explicit graphs traversed without repetition., O(bd) for implicit graphs with branching Space complexity O (| V |) if entire graph is traversed without repetition, O(longest path length searched) for implicit graphs without elimination of duplicate nodes BFS Time Complexity Since in the worst case breadth-first search has to consider all paths to all possible nodes the time complexity of breadth-first search is which is O (bd). The time complexity can also be expressed as O (| E | + | V |) since every vertex and every edge will be explored in the worst case. Space complexity University of Pune SE [IT] (2008 Course) 14 1. 2. 3. 4.

Data Structures and Files Teachers Laboratory Manual

Since all of the nodes of a level must be saved until their child nodes in the next level have been generated, the space complexity is proportional to the number of nodes at the deepest level. Given a branching factor b and graph depth d the asymptotic space complexity is the number of nodes at the deepest level, O (bd). When the number of vertices and edges in the graph are known ahead of time, the space complexity can also be expressed as O (| E | + | V |) where | E | is the cardinality of the set of edges (the number of edges), and | V | is the cardinality of the set of vertices. In the worst case the graph has a depth of 1 and all vertices must be stored. Since it is exponential in the depth of the graph, breadth-first search is often impractical for large problems on systems with bounded space. Conclusion: Thus we have studied representation of the graph using adjacency list and algorithms to perform DFS and BFS traversals.

University of Pune SE [IT] (2008 Course) 15

Data Structures and Files Teachers Laboratory Manual

Assignment No. 9 Title of Assignment : Representation of a given graph using adjacency list or array and finding the shortest path using Dijkstras algorithm. Objective: To understand the representation of a graph using adjacency matrix To understand the concept of finding shortest path between nodes using a Graph.

Problem Statement: Represent a given graph using adjacency matrix and find the shortest path using Dijkstras algorithm. Use the map of the area around the college as the graph. Identify the prominent land marks as nodes and find minimum distance to various land marks from the college as the source. Theory : Dijkstra's algorithm, is a graph search algorithm that solves the single-source shortest path problem for a graph with non negative edge path costs. It was named after its discoverer, Dutch computer scientist Edsger Dijkstra. This algorithm is often used in routing. For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. It can also be used for finding costs of shortest paths from a single vertex to a single destination vertex by stopping the algorithm once the shortest path to the destination vertex has been determined. In graph theory, the shortest path problem is the problem of finding a path between two vertices (or nodes) such that the sum of the weights of its constituent edges is minimized. An example is finding the quickest way to get from one location to another on a road map; in this case, the vertices represent locations and the edges represent segments of road and are weighted by the time needed to travel that segment. Formally, given a weighted graph (that is, a set V of vertices, a set E of edges, and a realvalued weight function f : E R), and one element v of V, find a path P from v to a v' of V so that is minimal among all paths connecting v to v' . The problem is also sometimes called the single-pair shortest path problem, to distinguish it from the following generalizations: University of Pune SE [IT] (2008 Course) 16

Data Structures and Files Teachers Laboratory Manual

The single-source shortest path problem, in which we have to find shortest paths from a source vertex v to all other vertices in the graph. The single-destination shortest path problem, in which we have to find shortest paths from all vertices in the graph to a single destination vertex v. This can be reduced to the single-source shortest path problem by reversing the edges in the graph. The all-pairs shortest path problem, in which we have to find shortest paths between every pair of vertices v, v' in the graph.

These generalizations have significantly more efficient algorithms than the simplistic approach of running a single-pair shortest path algorithm on all relevant pairs of vertices. Applications: 1. Traffic Information (Telephone Network) Systems use Dijkstras Algo in order to track the source and destinations from a given source and destination. 2. OSPF-OPEN SHORTEST PATH FIRST used in internet routing. It uses a link state in the individual areas that makeup the hierarchy. The computation is based on Dijkstras Algo which is used to calculate the shortest path tree inside each area of the network. 3. Shortest path algorithms are applied to automatically find directions between physical locations, such as driving directions on web mapping websites like Mapquest or Google Maps 4. If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities.

Design Analysis / Implementation Logic: Pseudocode: [I] ShortestPaths(v,cost,dist,n) //dist[j],1