Document Sample

Trees UNIT-3 Topics • Trees Binary trees terminology representation traversals • Graphs terminology representation graph traversals (dfs & bfs). Minimal Spanning trees. Trees-Introduction • A tree is a non-linear data structure in which data elements are arranged in a hierarchical manner. • A tree, is a finite set of nodes together with a finite set of directed edges that define parent-child (Hierarchical )relationships. Each directed edge connects a parent to its child. Tree -example Level 0 Root A Level 1 B C D Level 2 E F G H I Nodes={A,B,C,D,E,F,G,H,I} Edges={(A,B),(A,C),(A,D),(B,E),(B,F), (C, G),(D,H) ,(D,I)} Tree • A tree satisfies the following properties: 1. It has one designated node, called the root, that has no parent. 2. Every node, except the root, has exactly one parent. 3. A node may have zero or more children. 4. There is a unique directed path from the root to each node. 5 5 5 1 3 2 3 2 3 2 4 1 6 4 6 4 1 6 tree Not a tree Not a tree Tree Terminology Parent of x The node directly above node x in the tree A Child of x B C A node directly below node x in the tree Siblings D E F G H Nodes with common parent Root I Only node with no parent Leaf or External Node or terminal node A node with no children Internal Node (non leaf or non terminal) A node with children 6 Path A sequence of A connected nodes B C Ancestor of x A node on the path D E F G H from the root to x Descendent of x I A node on a path from x to a leaf Empty Tree A tree with no nodes 7 Height of Tree Number of edges on the longest path from the root to a leaf A Level 0 Depth of x Level 1 B C Number of ancestors x has D E F G Level 2 Level of x Number of edges on the path H I J Level 3 from the root to x (= depth) Level 4 k Degree of x Number of children x has • The height of a tree is the maximum level of any node in the tree – the empty tree has height zero A subtree of a node is a tree whose root is a child of that node 8 Binary Trees • A binary tree is a tree in which each node has at most two subtrees • A set of nodes T is a binary tree if either of the following is true – T is empty – Its root node has two subtrees, TL and TR, such that TL and TR are binary trees In a binary tree the maximum degree of any node is at most two Binary Tree Examples: A Root A Root Root C A B B D E Strictly Binary Tree: If every non-terminal node in a binary tree consist of left subtree and right subtree , then such a tree is called strictly binary tree. A A C B C B D E D E F Strictly Binary Tree Not a Strictly Binary Tree A strictly binary tree having n leaves always contain 2n-1 nodes Full Binary Trees • A full binary tree is either an empty binary tree or a strictly binary tree in which each level k, k > 0, has 2k nodes. A binary tree with n nodes and of depth d is a binary tree all of whose terminal nodes (leaf nodes) are at level d. Full binary tree of height h has: 2h+1 -1 nodes 2h leaves 2 h -1 non-leaves Complete Binary Trees • A complete binary tree is either an empty binary tree or a binary tree in which: 1. Each level k, k > 0, other than the last level contains the maximum number of nodes for that level, that is 2k. 2. The last level may or may not contain the maximum number of nodes. 3. If a slot with a missing node is encountered when scanning the last level in a left to right direction, then all remaining slots in the level must be empty. • Thus, every full binary tree is a complete binary tree, but the opposite is not true. Complete Binary Trees (Contd.) • Example showing the growth of a complete binary tree: Binary Tree Representation Static representation using arrays Dynamic representation using linked list Array representation of Binary trees: 1. An array can be used to store the nodes of a binary tree. 2. The nodes stored in an array are accessible sequentially. 3. The root node is always at index 0. 4. Then in successive memory locations the left child and right child are stored a 0 0 1 2 a b c b 1 c 2 Array Implementation 0 1 2 3 4 5 6 A A B C D E C B D E Node Location Root 0 Left Child of x 2 * location of x +1 Right Child of x (2 * location of x) + 2 Parent of x (location of x -1)/2 CISC 235 Topic 3 15 [0] A Sequential Representation [1] B [2] C (1) waste space (2) insertion/deletion [3] D [0] A A problem [4] E Skewed [1] B [5] F binary tree [2] -- [6] G B [3] C A [7] H [4] -- [8] I C [5] -- [6] -- B C [7] D D [8] -- . . D E F G E [15] E I H Linked Representation of Binary Trees Each node in the tree consists three parts: • Data • left child • right child The data field holds the value to be given, the lift child is link to left sub tree and right child is a link to right subtree A node in a binary tree data left data right left right A C Node structure: B struct Bnode { char data; D E Struct Bnode *left, *right; }; A B C D E Binary Search Tree Definition • A binary search tree is a nonempty binary tree that satisfies the following properties: 1. Each node has a key (or value), and no two nodes have the same key (i.e., all keys are distinct). 2. For every node x, all keys in the left subtree of x are smaller than that in x. 3. For every node x, all keys in the right subtree of x are larger than that in x. 4. The left and right subtrees of the root are also binary search trees Binary Trees 19 Basic Operations on Binary Search Tree Creating a Binary Tree Tree traversals Insertion of nodes Deletion of nodes Searching for the nodes Tree traversals 1. Tree traversal is one of the most common operation performed on tree data structure. 2. It is the way in which each node in the tree visited exactly once in a systematic manner. There are three popular ways of binary tree traversal. They are: 1.Preorder traversal 2.Inorder traversal 3.Postorder traversal Preoder, Inorder, Postorder • In Preorder, the root Preorder Traversal: is visited before (pre) 1. Visit the root the subtrees traversals 2. Traverse left subtree 3. Traverse right subtree • In Inorder, the root is Inorder Traversal: visited in-between left 1. Traverse left subtree 2. Visit the root and right subtree traversal 3. Traverse right subtree • In Preorder, the root Postorder Traversal: is visited after (pre) 1. Traverse left subtree 2. Traverse right subtree the subtrees traversals 3. Visit the root Traversal Sequences of Binary Trees Preorder: Root Left subtree right subtree A C Inorder: B Left subtree Root right subtree D E F Postorder: G H I Left subtree right subtree Root 22 A C B D E F G H I Preorder Traversal: A B DG CEFHI [ root left right ] Inorder Traversal: B G D A E C H F I [ left root right ] Postorder Traversal: G D B E H I F C A [ left right root] Example A B E C F G D K H L M I J inorder(struct bnode *x) { if(x!=NULL) {inorder(x->left); printf("%3d",x->data); preorder(struct bnode *x) inorder(x->right); { } if(x!=NULL) } {printf("%3d",x->data); preorder(x->left); preorder(x->right); } } postorder(struct bnode *x) { if(x!=NULL) {postorder(x->left); postorder(x->right); printf("%3d",x->data); }} search(root,ele) • Search begins at the root • If the root is NULL, the search tree is empty and the search fails. • If key is less than the root, then left subtree is searched • If key is greater than the root, then right subtree is searched • If key equals the root, then the search terminates successfully 20 10 40 6 15 30 Search for 8 2 8 25 int search(struct bnode *x,int ele) { if(x!=NULL) { if(x -> data == ele) return 1; else if(ele > x -> data ) search(x->right,ele); else search(x->left,ele); } else return 0;} insert(root,ele) • To insert a new element into a binary search tree, we must first verify that its key does not already exist by performing a search in the tree • If the search is successful, we do not insert • If the search is unsuccessful, then the element is inserted at the point the search terminated Insert 35 20 10 40 6 15 30 2 8 25 35 struct bnode *insert(struct bnode *x,int y) { if(x==NULL) {x=malloc(sizeof(struct bnode)); x->data=y; x->left=NULL; x->right=NULL; }else {if(y < x->data) x->left=insert(x->left,y); else if( y> x->data) x->right=insert(x->right,y); else{printf("\n Duplicate data ");} return(x); } delete(root,ele) • For deletion, there are three cases for the element to be deleted: 1. Element is a leaf. 2. Element is in a degree 1 node (i.e., has exactly one nonempty subtree). 3. Element is in a degree 2 node (i.e., has exactly two nonempty subtrees). Case 1: Delete a Leaf node • For case 1, we can simply discard the leaf node. • Example, delete a leaf element. key=7 20 10 40 6 15 30 2 8 18 25 35 7 Case 2: Delete from a Degree 1 Node 20 Delete 40 10 40 6 15 30 2 8 18 25 20 Delete 15 10 6 15 30 2 8 18 25 Case 3: Delete from a Degree 2 Node 20 10 40 6 15 30 2 8 18 25 35 7 • Replace with the largest key in the left subtree (or the smallest in the right subtree) 20 8 40 6 15 30 2 8 18 25 35 7 struct bnode* delet(struct bnode* x,int ele) { if(x!=NULL){ if(x->data < ele) x ->right = delet(x->right,ele); else if(x ->data > ele) x -> left = delet(x->left,ele); else { if(x->left!=NULL && x->right!=NULL){ struct bnode *q = findmax(x->left); x->data = q->data; x->left=delet(x->left,q->data);} else if(x->left!=NULL) x = x -> left; else x = x -> right; }} return x;} struct bnode* findmax(struct bnode *x){ if(x == NULL || x -> right == NULL) return x; else return findmax(x->right);} #include<stdio.h> #include<alloc.h> struct bnode {int data; struct bnode *left,*right; }*root,*t; int n,i; struct bnode * insert(struct bnode * , int); struct bnode* delet(struct bnode * , int); int search(struct bnode* ,int); struct bnode* findmax( struct bnode*); main() {int ch,ele,k; clrscr(); t=root=NULL; while(1) {printf("\n**** M E N U**** \n"); printf("1.INSERT\n2.RECURSSIVE TRAVERSE\n3.SEARCH\n4.DELETE\n5.E XIT\n"); printf("Enter your choice: "); scanf("%d",&ch); switch(ch) {case 1: printf("Enter how many elements u want to insert:"); scanf("%d",&n); printf("Enter tree elements: "); case 3:printf(" enter an elt to be searched"); for(i=1;i<=n;i++) scanf("%d",&ele); {scanf("%d",&ele); k=search(t,ele); t=insert(t,ele); if(k==1) printf("element is found"); }break; else printf("not found"); break; case 2: if(t==NULL) case 4: printf(" enter an elt to be deleted"); printf("**** TREE IS EMPTY****"); scanf("%d",&ele); Else {printf("INORDER :"); t=delet(t,ele); break; inorder(t); case 5:exit(); printf("\nPREORDER :"); }}} preorder(t); printf("\nPOSTORDER :"); postorder(t); }break; #include "stdio.h" bnode* delet(bnode* root,int ele){ struct node{ int data; if(root){ struct node *left,*right;}; if(root->data < ele) typedef struct node bnode; root ->right = delet(root->right,ele); bnode* getnode(int ele){ bnode *q = (bnode*) malloc(sizeof(bnode)); else if(root ->data > ele) if(q){ q -> data = ele;q -> left = NULL; root -> left = delet(root->left,ele); q -> right = NULL; return q;} else { else{ printf("\n Unable to create the node"); if(root->left && root->right){ exit(0);} return 0;} bnode *q = findmax(root->left); bnode* findmax(bnode *root){ root->data = q->data; if(root == NULL || root -> right == NULL) root->left=delet(root->left,q->data);} return root; else if(root->left) else return findmax(root->right);} void preorder(bnode *root){ root = root -> left; if(root){ printf("%5d",root->data); else root = root -> right; }} preorder(root->left);preorder(root->right);}} return root;} void inorder(bnode *root){ if (root){ inorder(root->left); bnode* insert(bnode *root,int ele){ printf("%5d",root->data);inorder(root->right);}} if(!root){bnode *q = getnode(ele); root = q;} void postorder(bnode *root){ if(root){postorder(root->left); else if(root->data < ele) printf("%5d",root->data);postorder(root->right);}} root->right = insert(root->right,ele); int search(bnode *root,int ele){ else if(root -> data > ele) if(root){if(root -> data == ele) return 1; root -> left = insert(root -> left,ele); else if(root -> data < ele) search(root->left,ele); else{printf("\n Duplicate data ");} else search(root->right,ele);} return 0;} return root;} #include "stdio.h" #include "conio.h" #include "btree.h" int menu() { int ch;clrscr(); printf("\n Binary Search Tree Operations :"); printf("\n\t 1->create 2 -> insert \n\t 3 -> Delete case 4:printf("\n Enter element to search:"); \n\t 4 -> search"); scanf("%d",&ele); printf("\n\t 5 -> preorder \n\t 6 ->inorder\n\t 7 -> if(search(root,ele)) postorder \n\t 8->exit"); printf("\n ELement found "); printf("\n Enter your choice :"); else scanf("%d",&ch); printf("\n Element not found"); return ch;} break; void main(){int ch,ele; bnode *root = NULL; case 5: preorder(root); do{ch = menu();switch(ch){ break; case 1: //root = create(root);break; case 6: inorder(root);break; case 2: printf("\n Enter element :"); case 7: postorder(root);break; scanf("%d",&ele);root = insert(root,ele); case 8:break; break; default : printf("\n Invalid choice. try again "); case 3: printf("\n Enter element :"); } scanf("%d",&ele); getch(); root = delet(root,ele); }while(ch!=6); break; } Construction of binary tree for arithmetic expressions While constructing an arithmetic expression into binary tree the operators are placed as interior nodes and operands becomes exterior nodes. Ex: A+B + A B Preorder traversal (prefix): A+B*C +A*BC + Postorder traversal(postfix) * ABC*+ A Inorder traversal(infix) C A+B*C B Applications of Trees • Trees are very important data structures in computing. • They are suitable for: – Hierarchical structure representation, e.g., • File directory. • Organizational structure of an institution. • Class inheritance tree. – Problem representation, e.g., • Expression tree. • Decision tree. – Efficient algorithmic solutions, e.g., • Search trees. • Efficient priority queues via heaps. Introduction to Graphs •A graph is a collection of nodes (or vertices) and edges (or arcs) •Definition: A graph G consists of set of all vertices (nodes) V, and set of all edges (arcs) (pair of elements from V) E. G = (V ,E) 1 2 5 3 4 V = { 1, 2, 3, 4, 5 } E = { (1,2) ,(1,3) , (1,4) ,(2,5) ,(3,4),(4,5)} Graph terminology • A directed graph (digraph) is one in which the edges have a direction 1 2 V={1,2,3,4,5} E={ (1,2) ,(1,3),(3,4),(4,1) ,(5,2) ,(5,4)} 5 3 4 • An undirected graph is one in which the edges do not have a direction • Adjacent nodes: If two nodes are connected by an edge, they are neighbors (and the nodes are adjacent to each other) • The size of a graph is the number of nodes in it • The empty graph has size zero (no nodes) • Self loop: If there is an edge whose starting and end vertices are same, that is, (vi ,vi) is an edge , then it is called a self loop (loop). • Parallel edges: If there are more than one edges between the same pair of vertices, then they are known as the parallel edges. • Simple graph: A graph if it does not have any self loop or parallel edges is called simple graph. • Weighted graph: A graph is termed as weighted graph if all the edges in it are labelled with some weights. • A path is a list of edges such that each node (but the last) is the predecessor of the next node in the list • A cycle is a path whose first and last nodes are the same. or If there is a path containing one or more edges which starts from a vertex vi and terminates at same vertex then it is called cycle. • Acyclic graph: A graph with no cycles is called acyclic graph. • The degree of a node is the number of edges it has • For directed graphs, – If a directed edge goes from node S to node D, we call S the source and D the destination of the edge • The edge is an out-edge of S and an in-edge of D – The in-degree of a node is the number of in-edges it has – The out-degree of a node is the number of out-edges it has • Isolated vertex: a vertex with degree zero. • Complete graph: If there are edges from any vertex to all other vertices , then that graph is called complete. A complete graph with n vertices will have n(n-1)/2 edges. • Connected graph: An undirected graph is connected if there is a path from every node to every other node • A directed graph is strongly connected if there is a path from every node to every other node. If there is a path from vi to vj then there must exist path from vj to vi. • A directed graph is weakly connected if the underlying undirected graph is connected • Node X is reachable from node Y if there is a path from Y to X Differences between tree and graph Trees graphs 1. parent-child relationship 1. No parent-child relationship 2. No cycles 2. Graph may contain cycles 3. No self loops 3. Graph may contain self loops 4. Only one path exists in any 4. There may multiple paths pair of vertices. exists in any pair of vertices. 5. The number of edges in a 5. A graph may contain more tree is precisely one less edges than vertices. than the number of nodes Representation of Graphs There are two ways to represent graphs: Adjacency matrix Adjacency List Adjacency Matrix: The adjacency matrix A for a graph G=(V,E) with n vertices, is an nXn matrix of bits, such that Aij=1 , if there is an edge from Vi to Vj Aij=0 , if no edge Adjacency matrix Representation of A Graph C Set of vertices = { A, B, C, D, E } B Set of edges={(A,B),(A,C),(A,D),(B,D),(B,D), (C,D),(C,E),(D,E)} D E Undirected graph Adjacency Matrix Adjacency Matrix is a bit matrix which contains entries of only A B C D E 0 and 1 A 0 1 1 1 0 The connected edge between two B 1 0 1 1 0 vertices is represented by 1 C 1 1 0 1 1 and absence of edge is D 1 1 1 0 1 represented by 0. E 0 0 1 1 0 Adjacency matrix of an undirected graph is symmetric. Linked List Representation A B C D NULL B A C D NULL A B D E NULL C D A B C E NULL A N E C D NULL B C D E graph Adjacency Adjacency list matrix graph Adjacency Adjacency list matrix Graph Traversal Techniques There are two standard graph traversal techniques: Depth-First Search (DFS) Breadth-First Search (BFS) • In both DFS and BFS, the nodes of the undirected graph are visited in a systematic manner so that every node is visited exactly one. • Both BFS and DFS give rise to a tree: – When a node x is visited, it is labeled as visited, and it is added to the tree – If the traversal got to node x from node y, y is viewed as the parent of x, and x a child of y Breadth-First Search • BFS follows the following rules: 1. Select an unvisited node x, visit it, have it be the root in a BFS tree being formed. Its level is called the current level. 2. From each node z in the current level, in the order in which the level nodes were visited, visit all the unvisited neighbors of z. The newly visited nodes from this level form a new level that becomes the next current level. 3. Repeat step 2 until no more nodes can be visited. 4. If there are still unvisited nodes, repeat from Step 1. 0 1 0 2 4 2 1 4 9 5 9 10 10 5 7 11 8 6 7 8 11 6 BFS Tree Graph G Implementation of BFS • Observations: – the first node visited in each level is the first node from which to proceed to visit new nodes. • This suggests that a queue is the proper data structure to remember the order of the steps. BFS (Pseudo Code) BFS(input: graph G) { Queue Q; Integer x, z, y; while (G has an unvisited node x) { visit(x); Enqueue(x,Q); while (Q is not empty){ z := Dequeue(Q); for all (unvisited neighbor y of z){ visit(y); Enqueue(y,Q); } } } } Depth-First Search • DFS follows the following rules: 1. Select an unvisited node x, visit it, and treat as the current node 2. Find an unvisited neighbor of the current node, visit it, and make it the new current node; 3. If the current node has no unvisited neighbors, backtrack to the its parent, and make that parent the new current node; 4. Repeat steps 3 and 4 until no more nodes can be visited. 5. If there are still unvisited nodes, repeat from step 1. 0 1 DFS Tree 0 2 1 4 4 9 10 5 7 2 11 8 5 9 Graph G 6 7 11 6 8 10 Implementation of DFS • Observations: – the last node visited is the first node from which to proceed. – Also, the backtracking proceeds on the basis of "last visited, first to backtrack too". – This suggests that a stack is the proper data structure to remember the current node and how to backtrack. DFS (Pseudo Code) DFS(input: Graph G) { Stack S; Integer x, t; while (G has an unvisited node x){ visit(x); push(x,S); while (S is not empty){ t := peek(S); if (t has an unvisited neighbor y){ visit(y); push(y,S); } else pop(S); } } } Spanning Trees A spanning tree of a graph is just a subgraph that contains all the vertices and is a tree. A graph may have many spanning trees. Graph A Some Spanning Trees from Graph A or or or Minimum Spanning Trees The Minimum Spanning Tree for a given graph is the Spanning Tree of minimum cost for that graph. Weighted Graph Minimum Spanning Tree 7 2 2 5 3 3 4 1 1 Algorithms to find Minimum- Spanning Trees - Kruskal‘s Algorithm - Prim‘s Algorithm Kruskal‘s Algorithm 1. Each vertex is in its own cluster 2. Take the edge e with the smallest weight - if e connects two vertices in different clusters, then e is added to the MST and the two clusters, which are connected by e, are merged into a single cluster - if e connects two vertices, which are already in the same cluster, ignore it 3. Continue until n-1 edges were selected 5 A B 4 6 2 2 D 3 C 3 1 2 E F 4 Prim‘s Algorithm 1. All vertices are marked as not visited 2. Any vertex v you like is chosen as starting vertex and is marked as visited (define a cluster C) 3. The smallest- weighted edge e = (v,u), which connects one vertex v inside the cluster C with another vertex u outside of C, is chosen and is added to the MST. 4. The process is repeated until a spanning tree is formed 5 A B 4 6 2 2 D 3 C 3 1 2 E F 4 Applications of Graphs • Electronic circuits – Printed circuit board – Integrated circuit • Transportation networks – Highway network – Flight network • Computer networks – Local area network – Internet – Web • Databases – Entity-relationship diagram Assignment - 3 1. Explain the representation of graph using adjacency matrix. Give the necessary algorithm. 2. Write and explain the breath first traversal and depth first traversal in a graph with algorithm 3. Write notes on spanning tree. Write and explain the algorithms to find minimal cost. 4. Write recursive functions in C for preorder, inorder and post order traversals of a binary tree. 5. Explain with an example how an element is inserted and deleted from a binary search tree.

DOCUMENT INFO

Shared By:

Categories:

Tags:

Stats:

views: | 16 |

posted: | 10/3/2012 |

language: | |

pages: | 65 |

OTHER DOCS BY vijay.ravipati

Docstoc is the premier online destination to start and grow small businesses. It hosts the best quality and widest selection of professional documents (over 20 million) and resources including expert videos, articles and productivity tools to make every small business better.

Search or Browse for any specific document or resource you need for your business. Or explore our curated resources for Starting a Business, Growing a Business or for Professional Development.

Feel free to Contact Us with any questions you might have.