C S 1 1 3 2 Design: - Data Structures and Software
C S 1 1 3 2 Design: - Data Structures and Software
Introduction to Graphs
A graph is a finite set of nodes with edges between nodes Formally, a graph G is a structure (V,E) consisting of
a finite set V called the set of nodes, and a set E that is a subset of VxV. That is, E is a set of pairs of the form (x,y) where x and y are nodes in V
Examples of Graphs
V={1,2,3,4,5} E={(1,2), (2,3), (1,4), (4,1), (3,3), (5,4)}
2 3 5 4
When (x,y) is an edge, we say that x is adjacent to y. 1 is adjacent to 2. 2 is not adjacent to 1. 4 is not adjacent to 3.
3
Trees
A tree is a connected acyclic undirected graph. The following are three trees:
2 1
7
5 12 3 4 6 11
10
A[15] : 105 The First is A[0] 11 And last is A[14] And Now we have two array one of the is bigger than 29 that is in the right side So (0+14)/2And is the other4 one has 7 19 int that all of the are smaller than 29 89 124 A[7] which is equal To 29
1 8
14
23
40
91
110
200
Illustration of Insert
15 8 2 6 3 7 11 10 12 14 20 27 22 30 3 2 8 11 15 20 27 22 14 30
6
7
10 12
25
Before inserting 25
After inserting 25
Creating a tree
struct btnode *root;
struct btnode *mynode = (struct btnode *) malloc (sizeof(struct btnode)); root = mynode;
// use root to access the tree, like head for a linked list
Creating nodes
struct node * NewNode(int data)
{ struct node *mynode = (struct node *) malloc (sizeof(struct node)); mynode->data = data; mynode->left_p = NULL; mynode->right_p = NULL; return(node); }
Insert function
Inorder Traversal: 1. Traverse left subtree 2. Visit the root 3. Traverse right subtree Postorder Traversal: 1. Traverse left subtree 2. Traverse right subtree 3. Visit the root
Inorder:
10
12
Postorder:
6
11
4 5 6 3 1 8 7 9 11 10 12
Postorder: 4 6 5 3 8 11 12 10 9 7 1
12
27 30
12 11 8 22 30 27 20 15
This is no coincidence
As a general rule, if you output the keys (data) of the nodes of a BST using inorder traversal, the data comes out sorted in increasing order
Note: A max-heap has the same definition except that the Key of every node is >= the keys of the children
Search function