Download presentation
Presentation is loading. Please wait.
Published byYandi Johan Modified over 6 years ago
1
Unit - 3 Trees - Binary tress - Terminology - Representation
- Traversals Minimal Spanning trees. Graphs - Graph traversals (dfs & bfs).
2
Tree Nodes={A,B,C,D,E,f,G,H}
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. Example: Nodes={A,B,C,D,E,f,G,H} Edges={(A,B),(A,E),(B,F),(B,G),(B,H), (E,C),(E,D)} A B E C D F H G
3
Tree A tree satisfies the following properties:
It has one designated node, called the root, that has no parent. Every node, except the root, has exactly one parent. A node may have zero or more children. There is a unique directed path from the root to each node. 5 2 4 1 6 3 5 5 2 4 1 6 3 1 3 2 4 6 tree Not a tree Not a tree
4
Tree Terminology A H G F E D C B I Parent of x
The node directly above node x in the tree Child of x A node directly below node x in the tree Siblings Nodes with common parent Root Only node with no parent Leaf or External Node A node with no children Internal Node Nonleaf node A H G F E D C B I 4 4
5
A H G F E D C B I Path A sequence of connected nodes Ancestor of x
A node on the path from the root to x Descendent of x A node on a path from x to a leaf Empty Tree A tree with no nodes A H G F E D C B I 5 5
6
Number of edges on the longest path from the root to a leaf
Height of Tree Number of edges on the longest path from the root to a leaf Depth of x Number of ancestors x has Level of x Number of edges on the path from the root to x (= depth) Degree of x Number of children x has A B D H C E F G J I k Level 0 Level 1 Level 2 Level 3 Level 4 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 6 6
7
Binary Trees In a binary tree, 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 A binary tree is a tree in which no nodes can have more than two children
8
Binary Search Tree Definition
A binary search tree is a nonempty binary tree that satisfies the following properties: Each node has a key (or value), and no two nodes have the same key (i.e., all keys are distinct). For every node x, all keys in the left subtree of x are smaller than that in x. For every node x, all keys in the right subtree of x are larger than that in x. The left and right subtrees of the root are also binary search trees Figure 14.1 Binary Trees 8
9
Binary Search Tree ADT bnode* create(bnode* root);
bnode* insert(bnode* root,int ele); bnode* delete(bnode *root,int ele); int search(bnode *root,int ele); void preorder(bnode *root); void inorder(bnode *root); void postorder(bnode *root);
10
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 40 10 6 2 8 15 30 25 Search for 8
11
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 40 10 6 2 8 15 30 25 35
12
delete(root,ele) For deletion, there are three cases for the element to be deleted: Element is in a leaf. Element is in a degree 1 node (i.e., has exactly one nonempty subtree). Element is in a degree 2 node (i.e., has exactly two nonempty subtrees). Case 1: Delete from a Leaf For case 1, we can simply discard the leaf node. Example, delete a leaf element. key=7 20 40 10 6 2 8 15 30 25 35 7 18
13
Case 2: Delete from a Degree 1 Node
20 40 10 6 2 8 15 30 25 18 Delete 40 20 10 6 2 8 15 30 25 18 Delete 15
14
Case 3: Delete from a Degree 2 Node
20 40 10 6 2 8 15 30 25 35 7 18 Replace with the largest key in the left subtree (or the smallest in the right subtree) 20 40 8 6 2 15 30 25 35 7 18
15
Binary Tree Traversal Techniques
Three recursive techniques for binary tree traversal In each technique, the left subtree is traversed recursively, the right subtree is traversed recursively, and the root is visited What distinguishes the techniques from one another is the order of those 3 tasks Pre order Traversal In order Traversal Post order Traversal
16
Preoder, Inorder, Postorder
Preorder Traversal: Visit the root Traverse left subtree Traverse right subtree In Preorder, the root is visited before (pre) the subtrees traversals In Inorder, the root is visited in-between left and right subtree traversal is visited after (pre) Inorder Traversal: Traverse left subtree Visit the root Traverse right subtree Postorder Traversal: Traverse left subtree Traverse right subtree Visit the root
17
6 15 8 2 3 7 11 10 14 12 20 27 22 30 Assume: visiting a node
is printing its label Preorder: Inorder: Postorder:
18
bnode* delet(bnode* root,int ele){ if(root){
#include "stdio.h" struct node{ int data; struct node *left,*right;}; typedef struct node bnode; bnode* getnode(int ele){ bnode *q = (bnode*) malloc(sizeof(bnode)); if(q){ q -> data = ele;q -> left = NULL; q -> right = NULL; return q;} else{ printf("\n Unable to create the node"); exit(0);} return 0;} bnode* findmax(bnode *root){ if(root == NULL || root -> right == NULL) return root; else return findmax(root->right);} void preorder(bnode *root){ if(root){ printf("%5d",root->data); preorder(root->left);preorder(root->right);}} void inorder(bnode *root){ if (root){ inorder(root->left); printf("%5d",root->data);inorder(root->right);}} void postorder(bnode *root){ if(root){postorder(root->left); printf("%5d",root->data);postorder(root->right);}} int search(bnode *root,int ele){ if(root){if(root -> data == ele) return 1; else if(root -> data < ele) search(root->left,ele); else search(root->right,ele);} return 0;} bnode* delet(bnode* root,int ele){ if(root){ if(root->data < ele) root ->right = delet(root->right,ele); else if(root ->data > ele) root -> left = delet(root->left,ele); else { if(root->left && root->right){ bnode *q = findmax(root->left); root->data = q->data; root->left=delet(root->left,q->data);} else if(root->left) root = root -> left; else root = root -> right; }} return root;} bnode* insert(bnode *root,int ele){ if(!root){bnode *q = getnode(ele); root = q;} else if(root->data < ele) root->right = insert(root->right,ele); else if(root -> data > ele) root -> left = insert(root -> left,ele); else{printf("\n Duplicate data ");} return root;}
19
#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 \n\t 4 -> search"); printf("\n\t 5 -> preorder \n\t 6 ->inorder\n\t 7 -> postorder \n\t 8->exit"); printf("\n Enter your choice :"); scanf("%d",&ch); return ch;} void main(){int ch,ele; bnode *root = NULL; do{ch = menu();switch(ch){ case 1: //root = create(root);break; case 2: printf("\n Enter element :"); scanf("%d",&ele);root = insert(root,ele); break; case 3: printf("\n Enter element :"); scanf("%d",&ele); root = delet(root,ele); case 4:printf("\n Enter element to search:"); scanf("%d",&ele); if(search(root,ele)) printf("\n ELement found "); else printf("\n Element not found"); break; case 5: preorder(root); case 6: inorder(root);break; case 7: postorder(root);break; case 8:break; default : printf("\n Invalid choice. try again "); } getch(); }while(ch!=6);
20
Full binary tree A binary tree of height h with no missing nodes All leaves are at level h and all other nodes each have two children Complete binary tree A binary tree of height h that is full to level h – 1 and has level h filled in from left to right Balanced binary tree A binary tree in which the left and right subtrees of any node have heights that differ by at most 1
21
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.
22
Representation of binary tree
Sequential Representation : -- Tree Nodes are stored in a linear data structure like array. -- Root node is stored at index ‘0’ -- If a node is at a location ‘i’, then its left child is located at 2 * i + 1 and right child is located at 2 * i + 2 -- This storage is efficient when it is a complete binary tree, because a lot of memory is wasted. A B A B - C D E C D E
23
Tree structure using Doubly Linked List
/* a node in the tree structure */ struct node { struct node *lchild; int data ; struct node *rchild; }; -- The pointer lchild stores the address of left child node. -- The pointer rchild stores the address of right child node. -- if child is not available NULL is strored. -- a pointer variable root represents the root of the tree. Root
24
Introduction to Graphs
Definition: A simple graph G = (V, E) consists of V, a nonempty set of vertices, and E, a set of unordered pairs of distinct elements of V called edges. For each eE, e = {u, v} where u, v V. An undirected graph (not simple) may contain loops. An edge e is a loop if e = {u, u} for some uV.
25
Graph terminology A graph is a collection of nodes (or vertices) and edges (or arcs) Each node contains an element Each edge connects two nodes together (or possibly the same node to itself) and may contain an edge attribute A directed graph is one in which the edges have a direction An undirected graph is one in which the edges do not have a direction Note: Whether a graph is directed or undirected is a logical distinction—it describes how we think about the graph Depending on the implementation, we may or may not be able to follow a directed edge in the “backwards” direction
26
The size of a graph is the number of nodes in it
The empty graph has size zero (no nodes) If two nodes are connected by an edge, they are neighbors (and the nodes are adjacent to each other) 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 S is a predecessor of D, and D is a successor of S 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
27
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 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 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 A subset of the nodes of the graph is a connected component (or just a component) if there is a path from every node in the subset to every other node in the subset
28
Representation of Graph
Set of vertices = { A, B, C, D, E } Set of edges={(A,B),(A,C),(A,D),(B,D),(B,D), (C,D),(C,E),(D,E)} There are two ways of representing a graph in memory. Sequential Representation by means of Adjacency Matrix. Linked Representation by means of Linked List. A B C D E Adjacency Matrix Adjacency Matrix is a bit matrix which contains entries of only 0 and 1 The connected edge between two vertices is represented by 1 and absence of edge is represented by 0. Adjacency matrix of an undirected graph is symmetric. A B C D E A B C D E
29
Linked List Representation
B C D NULL B A C D NULL C A B D E NULL D A B C E NULL A N E C D NULL B C D E
30
graph Adjacency list Adjacency matrix
31
graph Adjacency list Adjacency matrix
32
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
33
Breadth-First Search BFS follows the following rules:
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. 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. Repeat step 2 until no more nodes can be visited. If there are still unvisited nodes, repeat from Step 1.
34
1 2 2 4 1 4 9 5 9 10 5 7 10 11 8 6 7 8 11 6 Graph G BFS Tree 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.
35
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); }
36
Depth-First Search DFS follows the following rules: Select an unvisited node x, visit it, and treat as the current node Find an unvisited neighbor of the current node, visit it, and make it the new current node; If the current node has no unvisited neighbors, backtrack to the its parent, and make that parent the new current node; Repeat steps 3 and 4 until no more nodes can be visited. If there are still unvisited nodes, repeat from step 1.
37
1 DFS Tree 2 1 4 9 4 5 7 10 2 11 9 8 5 6 Graph G 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.
38
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); }
39
Some Spanning Trees from Graph A
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
40
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
41
Kruskal‘s Algorithm 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
42
5 A B 4 6 2 2 D C 3 1 2 3 E F 4
43
Prim‘s Algorithm 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) 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
44
5 A B 4 6 2 2 D C 3 1 2 3 E F 4
46
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
47
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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.