0% found this document useful (0 votes)
51 views

Cds Unit 5 Notes

Trees are hierarchical data structures that store elements in a parent-child relationship. There are several types of trees including general trees, binary trees, and binary search trees. Binary trees restrict each node to have at most two children while binary search trees impose the additional constraint that the left child must be less than the parent and right child greater than the parent. Graphs are non-hierarchical data structures that represent relationships between elements through edges. They can be directed or undirected and represented through adjacency matrices or lists. Common graph algorithms include breadth-first search and depth-first search.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Cds Unit 5 Notes

Trees are hierarchical data structures that store elements in a parent-child relationship. There are several types of trees including general trees, binary trees, and binary search trees. Binary trees restrict each node to have at most two children while binary search trees impose the additional constraint that the left child must be less than the parent and right child greater than the parent. Graphs are non-hierarchical data structures that represent relationships between elements through edges. They can be directed or undirected and represented through adjacency matrices or lists. Common graph algorithms include breadth-first search and depth-first search.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Subject: C Programming and Data Structures

Unit – 5
What are Trees?

A tree is a Hierarchical data structure that naturally hierarchically stores the


information. The Tree data structure is one of the most efficient and mature. The nodes
connected by the edges are represented.

Properties of Tree:

Every tree has a specific root node. A root node can cross each tree node. It is called
root, as the tree was the only root. Every child has only one parent, but the parent can
have many children.

Types of Trees in Data Structure

1. General Tree

If no constraint is placed on the tree’s hierarchy, a tree is called a general tree. Every
node may have infinite numbers of children in General Tree. The tree is the super-set
of all other trees.

2. Binary Tree

The binary tree is the kind of tree in which most two children can be found for each
parent. The kids are known as the left kid and right kid. This is more popular than most
other trees. When certain constraints and characteristics are applied in a Binary tree,
a number of others such as AVL tree, BST (Binary Search Tree), RBT tree, etc. are
also used. When we move forward, we will explain all these styles in detail.

.
.
3. Binary Search Tree

Binary Search Tree (BST) is a binary tree extension with several optional restrictions.
The left child value of a node should in BST be less than or equal to the parent value,
and the right child value should always be greater than or equal to the parent’s value.
This Binary Search Tree property makes it ideal for search operations since we can
accurately determine at each node whether the value is in the left or right sub-tree.
This is why the Search Tree is named.

4. AVL Tree
5. Red-Black Tree
6. N-ary Tree, etc..,

Tree Terminology

Advantages of Tree

1. The tree reflects the data structural connections.


2. The tree is used for hierarchy.
3. It offers an efficient search and insertion procedure.
4. The trees are flexible. This allows subtrees to be relocated with minimal effort.
What is a Binary Tree?

A binary tree is a tree data structure composed of nodes, each of which has at most,
two children, referred to as left and right nodes. The tree starts off with a single node
known as the root.

Definition: A binary tree is either empty or consists of a node called the root together
with two binary trees called the left subtree and the right subtree.

• If h = height of a binary tree,


max # of leaves = 2h
max # of nodes = 2h + 1 - 1

• A binary tree with height h and 2h + 1 - 1 nodes (or 2h leaves) is called a full
binary tree

Example:

Figure 4.6: Examples of complete, incomplete binary trees


Common operations

Following is a list of common operations that can be performed on a binary tree:

1. Insertion:

2. Deletion:

3. Tree traversal:

Another frequently used tree operation is traversal. Tree traversal is the process of
visiting each node present in a tree. There are three methods of tree traversal:

1. In-order traversal ( Left, Root, Right )


2. Post-order traversal (Left, Right, Root )
3. Pre-order traversal (Root, Left, Right)

Example:
Implementation:

typedef struct node-tag


{
item-type info ;
struct node-tag * left ;
struct node-tag * right ;
} node-type ;

node-type * root ; /* pointer to root */


node-type * p ; /* temporary pointer */

void preorder(node-type * root)


{
if (root) {
visit (root) ;
preorder (root left) ;
preorder (root right) ;
}
}

inorder (node-type * root)


{
if (root) {
inorder (root left) ;
visit (root) ;
inorder (root right) ;
}
}

void postorder (node-type * root)


{
if (root) {
postorder (root left) ;
postorder (root right) ;
visit (root) ;
}
}

Exercise. Given a sequence of numbers:


11, 6, 8, 19, 4, 10, 5, 17, 43, 49, 31
Unit 5 Graph

1. Define a graph.
A graph is a non-linear data structure that represents less relationship between its
adjacent elements. There is no hierarchical relationship between the adjacent elements
in case of graphs.

2. List the two types of graphs.


• Directed graph
• Undirected graph

3. Name the different ways of representing a graph? Give examples


a. Adjacency matrix

b. Adjacency list.

4. Define directed graph.


If an edge between any two nodes in a graph is directionally oriented, a graph is called
as directed graph; it is also referred as a digraph.

5. Define a path in a graph.


A path in a graph is defined as a sequence of distinct vertices each adjacent to the next,
except possibly the first vertex and last vertex is different.

6. Define a cycle in a graph.


A cycle is a path containing at least three vertices such that the starting and the ending
vertices are the same.

7. Define a strongly connected graph.


A directed graph is said to be strongly connected if, for every pair of distinct vertices
there is a directed path from every vertex to every other vertex. It is also referred as a
complete graph.

8. Define a weakly connected graph.


A directed graph is said to be weakly connected graph, if any vertex doesn’t have a
directed path to any other vertices.

9. Define a weighted graph.


A graph is said to be weighted graph if every edge in the graph is assigned some weight
or value. The weight of an edge is a positive value that may be representing the distance
between the vertices or the weights of the edges along the path.

10. State the different ways of traversing a graph.


• Depth-first traversal(or) Depth-first search(DFS)
• Breath-first traversal(or)Breath-first search(BFS)
BFS algorithm

The algorithm works as follows:

1. Start by putting any one of the graph's vertices at the back of a queue.
2. Take the front item of the queue and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to
the back of the queue.
4. Keep repeating steps 2 and 3 until the queue is empty.

The graph might have two different disconnected parts so to make sure that we cover every vertex,
we can also run the BFS algorithm on every node

BFS example

Let's see how the Breadth First Search algorithm works with an example. We use an undirected
graph with 5 vertices.

Undirected graph with 5 vertices

We start from vertex 0, the BFS algorithm starts by putting it in the Visited list and putting all its
adjacent vertices in the stack.

Visit
start vertex and add its adjacent vertices to queue

Next, we visit the element at the front of queue i.e. 1 and go to its adjacent nodes. Since 0 has
already been visited, we visit 2 instead.

Visit
the first neighbour of start node 0, which is 1
Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the back of the queue and visit 3,
which is at the front of the queue.

Visit 2 which was added to queue earlier to add its neighbours

4
remains in the queue

Only 4 remains in the queue since the only adjacent node of 3 i.e. 0 is already visited. We visit it.

Visit
last remaining item in the stack to check if it has unvisited neighbours

Since the queue is empty, we have completed the Breadth First Traversal of the graph.

Depth First Search Algorithm

The DFS algorithm works as follows:

1. Start by putting any one of the graph's vertices on top of a stack.


2. Take the top item of the stack and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to
the top of the stack.
4. Keep repeating steps 2 and 3 until the stack is empty.
Depth First Search Example

Let's see how the Depth First Search algorithm works with an example. We use an undirected
graph with 5 vertices.

Undirected graph with 5 vertices

We start from vertex 0, the DFS algorithm starts by putting it in the Visited list and putting all its
adjacent vertices in the stack.

Visit
the element and put it in the visited list

Next, we visit the element at the top of stack i.e. 1 and go to its adjacent nodes. Since 0 has
already been visited, we visit 2 instead.

Visit
the element at the top of stack

Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.

Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.
Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.

After we visit the last element 3, it doesn't have any unvisited adjacent nodes, so we have
completed the Depth First Traversal of the graph.

0 After
we visit the last element 3, it doesn't have any unvisited adjacent nodes, so we have completed the
Depth First Traversal of the graph.

BFS pseudocode:

1. create a queue Q
2. mark v as visited and put v into Q
3. while Q is non-empty
4. remove the head u of Q
5. mark and enqueue all (unvisited) neighbours of u

DFS pseudocode:

1. DFS(G, u)
2. u.visited = true
3. for each v ∈ G.Adj[u]
4. if v.visited == false
a. DFS(G,v)
5. init() {
6. For each u ∈ G
7. u.visited = false
8. For each u ∈ G
9. DFS(G, u)
10. }
1
UNIT 5

Sorting and Searching


1. Explain the bubble sort with sample code

Bubble sort algorithm implementatio0n in C

#include <stdio.h>

int main()
{
int array[100], n, c, d, swap;

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);
for (c = 0 ; c < n - 1; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1])
/* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}

printf("Sorted list in ascending order:\n");

for (c = 0; c < n; c++)


printf("%d\n", array[c]);

return 0;
}

Input : 10 4 5 6 2 1 9 7 8
Output : 1 2 3 4 5 6 7 8 9 10
2
UNIT 5

2. Write a c code for Selection Sort


#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;

// One by one move boundary of unsorted subarray


for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first element


swap(&arr[min_idx], &arr[i]);
}
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions


int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n); return 0;
}
3
UNIT 5

6. Write a C code for insertion Sort

/* Insertion sort ascending order */

#include <stdio.h>

int main()
{
int n, array[1000], c, d, t;

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++) {


scanf("%d", &array[c]);
}

for (c = 1 ; c <= n - 1; c++) {


d = c;

while ( d > 0 && array[d-1] > array[d]) {


t = array[d];
array[d] = array[d-1];
array[d-1] = t;

d - - 0;
}
}

printf("Sorted list in ascending order:\n");

for (c = 0; c <= n - 1; c++) {


printf("%d\n", array[c]);
}

return 0;
}
4
UNIT 5

3. Explain Linear Search with C code?


A linear search, also known as a sequential search, is a method of finding an element
within a list. It checks each element of the list sequentially until a match is found or
the whole list has been searched.

A simple approach to implement a linear search is


• Begin with the leftmost element of arr[] and one by one compare x with each
element.
• If x matches with an element then return the index.
• If x does not match with any of the elements then return -1.

Implementing Linear Search in C

#include<stdio.h>

int main()
{
int a[20],i,x,n;
printf("How many elements?");
scanf("%d",&n);

printf("Enter array elements:n");


for(i=0;i<n;++i)
scanf("%d",&a[i]);

printf("nEnter element to search:");


scanf("%d",&x);

for(i=0;i<n;++i)
if(a[i]==x)
break;

if(i<n)
printf("Element found at index %d",i);
else
printf("Element not found");

return 0;
}
5
UNIT 5

4. Explain Binary Search with C code.

Consider an array of 10 elements as below.

Consider for example you want to search for 85 which is the sixth element (index
position 5) in the array. In this case, the recursive calls to the binary search
function will be performed as shown in the figure below.

As you can see the above diagram, the search range becomes smaller and smaller
with each recursive call of binary search function. The first call to binary
search function tries to find the search element in array position 0 to 9. In the second
call you chop the array in two slices and perform the search on elements from 5 to 9.
Search range on the third call is from position 5 to 6.
6
UNIT 5

Program

#include <stdio.h>
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l)/2;
// If the element is present at the middle itself
if (arr[mid] == x) return mid;
// If element is smaller than mid, then it can only be present
// in left subarray
if (arr[mid] > x) return binarySearch(arr, l, mid-1, x);
// Else the element can only be present in right subarray
return binarySearch(arr, mid+1, r, x);
}
// We reach here when element is not present in array
return -1;
}

int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}

You might also like