Arrow DSU_C Notes
Arrow DSU_C Notes
CHAPTER 2
SYLLABUS
2.1 SEARCHING
2.1.1 LINEAR SEARCH
2.1.2 BINARY SEARCH
2.2 SORTING
2.2.1 BUBBLE SORT
2.2.2 INSERTION SORT
2.2.3 SELECTION SORT
2.2.4 QUICK SORT
2.2.5 RADIX SORT
Linear search is the easiest search technique in which each element is scanned in a sequential manner to
locate the desired element.
In this method, search begins with the first available record and proceeds to the next available record
until we find the target key or conclude that it is not found. Linear search is also called as "sequential
search”.
Example:
Consider an array with 5 elements
We are searching for element 91. To search 91 the item 91 is compared with element at A[0] then A[1]
and so on untill we find the target value or reach to the end of array.
When item is found it displays the location of an item else displays item not found.
3 21 11 91 19
0 1 2 3 4
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10]={10,20,30,40,50,60,70,80,90,100};
int i,num,flag=1;
clrscr();
printf("LINEAR SEARCH");
printf("\n INPUT LIST:-\n");
for(i=0;i<=9;i++)
printf("%d\t",a[i]);
printf("\nEnter search element:");
scanf("%d",&num);
for(i=0;i<=9;i++)
{
if(num==a[i])
{
printf("\n Element found at %d index position ",i);
flag=0;
break;
}
}
if(flag==1)
printf("\n Element not found");
getch();
}
If both are equal then stop the search process. If both are not equal then divide list into two parts.
If the search element is less than mid position element then change the upper index value and use first
half of the list for further searching process.
If the search element is greater than mid position element than change the lower index value and use
second half of the list for further searching process.
Again find lower and upper index value and calculate mid value.
Repeat the process till element is found or lower index value is less than or equal to upper index value.
Step2:
lower=5,upper=9;
mid=5+9/2=7
S==X[7] i.e 80==80
Search successful.
Element 80 is placed at the index position 7.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10]={10,20,30,40,50,60,70,80,90,100};
int i,mid,num,upper=9,lower=0, flag=1;
clrscr();
printf("BINARY SEARCH");
printf("\n ARRAY ELEMENTS:-\n");
for(i=0;i<=9;i++)
{
printf("%d\t",a[i]);
}
printf("\nEnter search element:");
scanf("%d",&num);
while(lower<=upper)
{
mid=(upper+lower)/2;
if(num= =a[mid])
{
flag=0;
printf("\n Element found at %d index position ",mid);
break;
}
if(num>a[mid])
lower=mid+1;
else
upper=mid-1;
}
if(flag==1)
printf("\n Element not found");
getch();
}
}
Q] Find location of element ‘H’ by using binary search algorithm in the given list. [S-16]
B F D A C E I G H J (Correct steps - 4 marks)
Ans: Binary search requires sorted array.
Input string:- B,F,D,A,C,E,I,G,H,J
Sorted list:- A,B,C,D,E,F,G,H,I,J
Array X [10]: used to store elements, lower is lower index of array, upper is upper index of array.
Step 1:-
lower=0,upper=9 ; mid=9/2=4.5=4
H!=E (num!=X[mid])
H>E (num>X[mid])
lower = mid+1=5
Step 2:
lower=5,upper=9;
mid=5+9/2=7
H==X[7]
Search successful.
Element H is placed at the index position 7.
Iteration 1:
BEG = 0, END = 7, MID = (0 + 7)/2 = 3
Now, VAL = 29 and A[MID] = A[3] =11
A[3] is less than VAL, therefore, we now search for the value in the second half of the array.
So, we change the values of BEG and MID.
Iteration 2:
Now, BEG = MID + 1 = 4, END = 7, MID = (4 + 7)/2 =11/2 = 5; VAL = 29 and A [MID] =
A [5] = 21
A[5] is less than VAL, therefore, we now search for the value in the second half of the segment.
So, again we change the values of BEG and MID.
Iteration 3:
Now, BEG = MID + 1 = 6, END = 7, MID = (6 + 7)/2 = 6 Now, VAL = 29 and A [MID] = A [6]=29
So, Element 29 is found at 6th location in given array A[]={2,3,5,11,17,21,29,43}.
INTRODUCTION
Sorting: - Process by which a collection of items are arranged into ascending order or in
descending order.
1. Internal Sorting:
In this sorting technique, all the data is retained in main memory only and the
data can be accessed randomly. Elements to be sorted are stored in an integer
array. These elements are sorted using one of the sorting algorithms.
2. External Sorting:
External sorting is carried on secondary storage. External sorting becomes necessity
if the number of elements to be sorted is too large to fit in main memory.
Sorting Techniques:
Bubble Sort
Insertion Sort
Selection Sort
Quick Sort
Radix Sort
Sorting begins with 0th elements & it compares with 1st element in list. If 1st element is less than
0th element then interchange takes place. Like this all elements are compared with next element &
interchanged if required. At end of 1st pass largest element is placed at last position. In 2nd pass
again comparisons starts with 0th element & 2nd largest element is placed at second last position.
This process continues till list is in sorted order.
Let n be the number of elements in an array a[]. The first pass begins with the comparison of a[0]
with a[1]. If a[0] is greater than a[1], the two elements are exchanged. Larger one will be placed in
a[1] after first comparison. Comparison can move forward and after the last comparison of a[n-2]
and a[n-1], the largest element will be placed in a[n-1].
Selection sort is a very simple sorting method. In the ith pass, we select the lowest value element
among a[i], a[i+1], ….. , a[n-1] and we swap it with a[i]. As a result after ith pass, first i elements
will be in sorted order.
Algorithm:
}
}
#include <stdio.h>
#include<conio.h>
void selection_sort(int[],int);
void main()
{
int a[100],n,i;
clrscr();
printf("Enter the number of elements to be sorted: ");
scanf("%d",&n);
printf("enter the array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
selection_sort(a,n);
{
temp=a[i];
a[i]=a[pos];
a[pos]=temp;
}
}
}
Selection sort is not Data Sensitive. In ith pass, n-i comparisons will be needed to select the smallest element.
In insertion sort, sorting is done on the principal of inserting the element at it correct place in previously
sorted list.
In first pass, 1st index element is compared with 0th index element.
If 0th index element is greater than 1st index element then store 1st index element into a temporary
variable and shift 0th index element to its right by one position.
Then insert temporary variable value in 0th position.
In pass 2, compare 2nd index element with 0th index and then 1st index elements.
If required perform shift and insert operations.
In each pass fix one position and compare it with all elements placed before it.
Continue this process till last position element is compared with all elements placed before it.
Example-
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
insertion_sort(a,n);
for(i=0;i<n;i++)
{
printf("\t %d",a[i]);
}
getch();
}
for(i=1;i<n;i++)
{
temp=a[i];
{
a[j+1] = a[j];
}
a[j+1] = temp;
}
}
Quick sort is the fastest internal sorting algorithm with the time complexity = 0(n log n).
The basic algorithm to sort an array a [ ] of n elements can be described recursively as follows :
Radix Sorting: -
In this method, ten buckets (0-9) are used to sort elements of an input list.
All the elements are sorted according to their digit position from each element.
In pass one each element is placed inside the bucket with respect its unit position digit. After placing all
elements inside the buckets, read those from 0th bucket to 9th bucket.
In pass 2, elements are placed in buckets with respect to 10th position digit from each element.
In each pass one position is considered to arrange all the elements in bucket.
At the end of each pass, elements are collected from buckets and given as input to the next pass.
Total number of passes required for sorting is equal to maximum number of digits present in the largest
number from the input list.
Last pass gives sorted list after reading all elements from 0 th bucket to 9th bucket.
Algorithm:
{
1. bucket_no=(x/div)%10
2. insert x in bucket with bucket_no
}
Step5: Exit
{**Note: As radix sort cannot be applied on decimal number, consider all number without
decimal i.e. 873,234,729,359,458,379,320,422)**}
Ans:-
OR
ARROW COMPUTER ACADEMY DSU 8788335443
`
Q] Sort the given no. in ascending order using radix sort. Numbers: 348, 14, 614, 5381, 47
(Each pass- 1 Mark)
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],pos,i,n,value;
clrscr();
printf("enter no of elements in array of students:");
scanf("%d",&n);
printf("enter %d elements are:\n",size);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter the position where you want to insert the element:");
scanf("%d",&pos);
printf("enter the value into that poition:");
scanf("%d",&value);
if(pos>0 && pos<=n)
{
for(i=n-1;i>=pos-1;i--)
{
a[i+1]=a[i];
}
a[pos-1]=value;
printf("final array after inserting the value is\n");
for(i=0;i<=n;i++)
{
printf("%d\n",a[i]);
}
}
else
{
printf("Enter correct position");
}
getch();
}
printf("Resultant array:\n");
getch();
}
Ans:
Linked list:
It is linear collection of data elements.
Each element in linked list is called as ‘node’.
Each node contains two fields.
First is INFO which stores data & second is NEXT which is linked with address of next node in a
list.
This structure allows for efficient insertion or removal of elements from any position in the
sequence.
Q] Explain the concept of information, Next, Null Pointer and empty list with respect to link
list. (each term 1M) [S
14][W 16]
Q] Define the term: [S 15]
i) Node ii) Address iii) Null pointer iv) Next pointer for linked list.
Node: Each element in linked list is called as ‘node’. Each node contains two fields. First is
INFO which stores data & second is NEXT which is linked with address of next node in a
list.
Address: Address indicates location of node.
Info Field: It is used to store data inside the node.
Next Pointer: Holds the Address of the next node, which intern links the nodes together.
Null Pointer: It is used to specify end of the list. The last element of list contains NULL
pointer to specify end of list.
Empty List: A linked list is said to be empty if head (start) node contains NULL pointer.
Q] Explain insertion of new node at start and at end in singly linked list.
Q] Write an algorithm to insert a new node as the last of a singly linked list. Give example. [W 16]
Q] Write an algorithm to insert a new node at the beginning of a singly linked list. Give example. [W
14]
Ans:
Inserting node at start in the SLL (Steps):
In this operation, new node can be created and added at the beginning of a list. New node points
to existing first node and start points to newly added node.
1. Create New Node
2. Fill Data into “Data Field“
3. Make its “Pointer” or “Next Field” as NULL
4. Attach this newly Created node to the start.
a) Set the next field of new node to beginning of the linked list.
b) Change the reference pointer of the linked list (Head) to point to the new node.
5. Make new node as Starting node
struct node
{
int data;
struct node *next;
};
Insert it at Beginning:-
newNode->next = head;
head = newNode;
temp->next = newNode;
1. if ( head = =NULL)
then display "linked list is empty”.
2. Otherwise visit each node of linked list and display its data till end of the list
struct node *temp = head; // Assign a temporary pointer temp to starting node
while ( temp != NULL)
do
{
Display temp->data // display node information
temp=temp->next; // Next field of the node pointed by temp contains
the address of the next node.
}
Node to be deleted is node1.Create a temporary node as ‘temp’. Set ‘temp’ node with the address
of first node. Store address of node 2 in header pointer ‘start’ and then delete ‘temp’ pointer with
free function. Deleting temp pointer deletes the first node from the list.
Algorithm:
Point head to the second node
Set temp = head
head = head->next;
Make sure to free unused memory
free(temp); or delete temp;
2. Delete from end
Node to be deleted is node 3.Create a temporary node as ‘temp’ and ‘q’.
Set ‘temp’ node with the address of first node.
Traverse the list up to the second last node and mark the last node as ‘q’.
Store NULL value in address field of ‘temp’ node and then delete ‘q’ pointer with free function.
Deleting q pointer deletes the last node from the list.
Algorithm:-
Traverse to second last element
Change its next pointer to null
temp->next = temp->next->next;
Algorithm:-
Ans:
ALGORITHM:
1. Start
2. check if the list is empty or not
if head ==NULL
OUTPUT: “Zero nodes” and exit
else goto step 3
3. Set the head pointer to a temporary variable
temp=head
4. Traverse till the last node
In Doubly-linked list each node contains two links- one to the previous node and other to the next
node.
The previous link of the first node and the next link of the last node points to NULL.
In Doubly linked list, a node comprises of total three fields
EXAMPLE:
Advantages:
1. Traversal is done in both the directions,
2. Insertion and deletion can be easily performed.
3. Searching an element is faster.
4. It is easy to reverse the linked list.
Q] Draw representation of linear linked list, circular linked list and doubly linked list.
[S17]
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
}*head;
void display()
{
struct node *temp;
if(head==NULL)
{
Prof. Somwanshi A.A.
printf("\n List is Emplty");
}
temp=head;
printf("\n List is \n");
while(temp!=NULL)
{
printf("%d -> ",temp->data);
temp=temp->next;
}
printf("Null");
}
int main()
{
int data,n,i,key;
head=NULL;
printf("How many nodes u want to add in Linked List \n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter data value\n");
scanf("%d",&data);
create_list(data);
}
display(head);
if(searchNode(head,key) == 1)
printf("Search Found\n");
else
printf("Search Not Found\n");
return 0;
}
Q] Write a program to delete the Specific Element From the Linked List
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
}*head;
void display()
{
struct node *temp;
if(head==NULL)
{
printf("\n List is Emplty");
}
temp=head;
printf("\n List is \n");
while(temp!=NULL)
{
printf("%d -> ",temp->data);
temp=temp->next;
}
printf("Null");
}
int main()
{
int data,n,i,key;
head=NULL;
printf("How many nodes u want to add in Linked List \n");
scanf("%d",&n);
Prof. Somwanshi A.A.
for(i=0;i<n;i++)
{
printf("enter data value\n");
scanf("%d",&data);
create_list(data);
}
display(head);
deleteNode(key);
display(head);
return 0;
}
STACK AS AN ADT
Q] Describe the stack as an abstract datatype. 4M [S-17]
Ans:
An Abstract Data type is one where we can store elements and also perform certain operation
on those elements.
Stack provides such facilities.
Stack as an abstract data type contains stack elements such as array(list), stack top and its
operations such as initialize, empty, full, push, pop, display.
Q] Describe PUSH and POP operation on stack using array representation. [W 16]
Q] Write the procedure for implementing stack using arrays. [S 16]
(Relevant description - 4 marks)
Q] Describe the representation of stack using arrays. [W 15]
(Relevant description – 4M)
Ans:
1. Definition: Stack is a linear data structure which follows Last-In First- Out (LIFO)
principle where, elements are added and deleted from only one end called as stack top
2.
3. PUSH Operation:
a. If (top= =max-1)
then display “Stack overflow”
b. else
do top=top+1
a[top]=data
4. POP Operation:
a. If (top= = -1)
then display “Stack underflow”
b. else
ARROW COMPUTER ACADEMY DSU 8788335443
do Data= a[top]
Top=top-1
Q] State importance of top pointer in stack. Explain stack overflow and underflow. [S 16]
(Importance - 1 mark, overflow - 1 ½, underflow - 1 ½)
Q] Describe the term stack overflow and stack underflow with example. State any
four applications of stack.
[W 15]
(Description of stack overflow 3M, underflow 3M, any four applications each ½ M)
Ans.
Stack overflow:
When a stack is full and push operation is called to insert a new element, stack is said to be
in overflow state.
Recursion
Reversing String
Interrupt handling
Expression conversion & evaluation: Polish Notation
Stack machine
Matching parenthesis in an expression
Q] What is the effect of PUSH and POP operation on to the stack? The stack contains 10,
20, 22, 26, 28, 30 with 30 being at top of the stack. Show diagrammatically the effect of
PUSH 46, PUSH 48, POP, POP, POP, PUSH 82
[S-14]
Q] Write an algorithm to convert infix string into postfix (Fully parenthesized) (Any correct
algorithm indicating steps for conversion 4M) [W 15]
Ans:
1. Accept infix string as an input array and add the symbol ‘#’ at the end of the array
2. Read the string symbols one – by – one from left to right
3. If the current symbol is an operand, add it into postfix array
4. If the current symbol is left parenthesis ‘(‘, push it into operator stack
5. If the current symbol is an operator POP all the operators having precedence greater than or
equal to the current operator and add it to postfix array else PUSH the current operator into
operator stack.
6. If the current symbol is right parenthesis ‘)’, POP all the operators from operator stack and Add
it to the Postfix array till the respective left parenthesis is encountered
7. Repeat Steps 2 till 6, until the end of input array indicated by ‘#’ symbol.
8. Display Postfix expression for the given infix string.
ii)A*B-C^D+E/F
Step 2: Operators are moved between the two operands of the group 5*(6+2)-12/4
Recursion is the process of calling function by itself. A recursive function body contains
function call statement that calls itself repeatedly.
Applications:
1. Factorial of number 2. Tower of Hanoi 3. Fibonacci Series
Q) Explain how stack can be used to reverse a list using suitable example. [S
16]
(Description - 2 marks; Example - 2 marks)
Ans:
A simple application of stack is reversal of list. To reverse a list, the elements of list are pushed
onto the stack one by one as the element read from first to last. Once all elements are pushed
on the stack & they are popped one by one. Since the element last pushed in comes out first,
hence reversal of string occurs. Consider following example where a list contains elements as
{1, 2, 3, 4, 5, 6}. Every push operator will push an element on top of stack. Once all elements
are pushed, one can pop all elements and save it which results in reversing of list as {6, 5, 4, 3,
2, 1}.
Q] Define recursion. Write a ‘C’ program to calculate the factorial of number using
recursion.
(Definition – 2 Marks, Program – 6 Marks) [S 14]
Ans: A function is called by itself is called as recursion
int fact(int n)
{
if(n==1)
return 1;
else
return(n*fact(n-1));
}
return(n*fact(n-1)); This statement gives recursive call to the function. Each time when
factorial function is called stack stores the value of current local variables and then next
variable. If factorial of 5 then first time stack will have 5 then in 2nd call 4 … till the last call
stack gets the element. Once it is 1 all variable values are pop & result is calculated.
Q) Define recursion. Write a ‘C’ program for multiplication of natural numbers using recursion.
(Definition -1Mark, Logic of program- 3Marks) [S 15]
7*5=35
7+7+7+7+7
5+5+5+5+5+5+5
#include<stdio.h>
#include<conio.h>
int multiply(int,int);
void main()
{
int a,b,p;
clrscr();
printf("Enter any two integers: ");
scanf("%d%d", &a,&b);
p = multiply(a,b);
printf("Multiplication of two integers is %d",p);
Queue is a data structure where elements are inserted at one end known as “Rear” and
deleted from the other end known as “Front”.
Queue is FIFO (First In First Out).
Front: - This end is used for deleting an element from a queue. Initially front end is set to -1.
Front end is incremented by one when an element has to be deleted from queue.
Rear: - This end is used for inserting an element in a queue. Initially rear end is set to -1. rear
end is incremented by one when a new element has to be inserted in queue.
ARRAY REPRESENTATION
OPERATIONS ON QUEUE
initialize(): Initialize a queue by setting the values of rear and front to -1.
enqueue(): Inserts an element at the rear end of the queue.
dequeue(): Deletes the front element and returns the same.
empty(): It returns true (1) if the queue is empty and returns false (0) if the queue is not
empty.
full(): It returns true(1) if the queue is full and returns false(0) if the queue is not full.
display (): Prints the queue elements.
Q] Describe the queue as abstract data type. (Elements - 2 Marks, Operations – 2 Marks)
Ans: Queue is a data structure where elements are inserted at one end known as “Rear” and
deleted from the other end known as “Front”.
Queue is an abstract data type because it does not only allow storing elements but also allows
perform certain operation on these elements.
1. Front
2. Rear
3. array
initialize(): Initialize a queue by setting the values of rear and front to -1.
enqueue(): Inserts an element at the rear end of the queue.
dequeue(): Deletes the front element and returns the same.
empty(): It returns true (1) if the queue is empty and returns false (0) if the queue is not
empty.
full(): It returns true(1) if the queue is full and returns false(0) if the queue is not full.
display (): Prints the queue elements.
#include<stdio.h>
#include<conio.h>
#define MAX 3
int rear= -1;
int front= -1;
int arr[MAX];
void insert()
{
int x;
if(rear ==(MAX-1))
printf("\n queue is full");
else
{
printf("\n enter element to be inserted:");
scanf("%d", & x);
rear=rear+1;
arr[rear]=x;
if(front==-1)
{
front=0;
}
}
}
void del()
{
int data;
if(front==-1)
printf("\n queue is empty");
else
{
data=arr[front];
printf("\n deleted element is %d",data);
if(front==rear)
{
front=-1;
rear=-1;
}
else
front=front+1;
}
}
APPLICATION OF QUEUE
1) Simulation
2) CPU scheduling in multiprogramming and time sharing systems.
3) Queue is used in round robin scheduling algorithm
4) Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
5) In real life, Call Centre phone systems will use Queues, to hold people calling them in an
order, until a service representative is free.
6) Handling of interrupts in real-time systems.
Queue Full:
Before inserting an element in queue 1st check whether space is available for new element in
queue. This can be done by checking position of rear end. A queue is full when its rear pointer
points to max -1 position. Max is maximum number of elements in a queue. If rear pointer is
not equal to max-1 then a new element can be added to a queue. If queue is full then new
element cannot be added to a queue.
Example:-
Consider max=4. First element is stored at 0th position and last element is stored at 3 rd
position in queue. In the diagram given below rear pointer is pointing to max-1 (3) position so
queue is full.
Size of queue = 4
Queue Empty: Before deleting any element from queue check whether there is an element in
the queue. If no element is present inside a queue, then front is set to -1 and queue is said to
be empty.
Size of queue = 4
0 1 2 3
Front = -1
Circular Queue:
A queue, in which the last node is connected back to the first node to form a cycle, is called as
circular queue.
Initially front and rear both are initialized to -1 to represent queue empty.
First element inserted in circular queue is stored at 0th index position pointed by rear
pointer. For the very first element, front pointer is also set to 0th position.
Whenever a new element is inserted in a queue rear pointer is incremented by one.
Before inserting an element, queue full condition is checked. If rear is set to max-1 position
and front is set to 0 then queue is full. If queue is full then new element cannot be added in a
queue.
If rear is pointing to max-1 and no element is present at 0th position then rear is set to 0th
position to continue cycle.
Circular queue has advantage of utilization of space. Before inserting an element in circular
queue front and rear both the pointers are checked. So if it indicates any empty space
anywhere in a queue then insertion takes place. Circular queue is full only when there is no
empty position in a queue.
Insert operation:
Step 1: Check for queue full
if rear=max–1 and front=0 then circular queue is full and insertion operation is not possible.
otherwise go to step 2
Step 2: Check position of rear pointer
If rear=max–1 then set rear=0 otherwise
increment rear by 1 i.e.(rear = rear + 1)
Step 3: Insert element at the position pointed by rear pointer.
arr[rear]=element;
Step 4: Check the position of front pointer
If front= –1 then set front as 0.
Delete operation:-
Step 1: Check for queue empty
if (front == -1)
then circular queue is empty and deletion operation is not possible.
otherwise go to step 2
Step 2: Delete the element.
element = arr [front]
Step 3: Check for position of front and rear pointers.
if (front == rear)
then
set front=rear=-1
Step 4: Check position of front
if (front == Max-1)
then set front=0;
otherwise
front = front+1
Step 4: Stop
Advantage:-
It allows insertion of an element in a queue when queue has empty space in it.
Before insertion, it checks for circular queue full. If queue is not full then it performs insert
operation to add an element in it.
A priority Queue is a collection of elements where each element is assigned a priority and the
order in which elements are added into the queue.
The rules for processing the elements of priority queue are:
1) An element with higher priority is processed before any element of lower priority.
2) Two elements with the same priority are processed according to the order in which they
are added to the queue (FCFS).
Array representation:
Array element of priority queue has a structure with data, priority and order. Priority queue
with 5 elements:
Above figure shows Priority Queue with 5 elements, where B & C have same priority number.
Each node in above priority queue contains three items.
An example where priority queue are used is in operating systems. The operating system has
to handle a large number of jobs. These jobs have to be properly scheduled. The operating
system assigns priorities to each type of job. The jobs are placed in a queue and the job with
the highest priority will be executed first.
Advantages:
1) Preferences to the higher priority process are added at the beginning. High priority process
executes first.
2) Keep the list sorted in increasing order.
Tree data structure is a collection of data (Node) which is organized in hierarchical structure
recursively.
Definition:
A tree is a finite set of nodes where starting node is called as Root node of the tree and the
remaining nodes are represented as two sub-trees (left sub-tree and right sub-tree) of the root node.
In tree data structure, every individual element is called as Node. Node in a tree data structure stores
the actual data of that particular element and link to next element in hierarchical structure.
In a tree data structure, if we have N number of nodes then we can have a maximum of N-1 number of
links.
Example
Terminology
In a tree data structure, we use the following terminology...
1. Root
In a tree data structure, the first node is called as Root Node. Every tree must have a root node. We
can say that the root node is the origin of the tree data structure. In any tree, there must be only one
root node. We never have multiple root nodes in a tree.
3. Parent
In a tree data structure, the node which is a predecessor of any node is called as PARENT NODE. In
simple words, the node which has a branch from it to any other node is called a parent node. Parent
node can also be defined as "The node which has child / children".
4. Child
In a tree data structure, the node which is descendant of any node is called as CHILD Node. In simple
words, the node which has a link from its parent node is called as child node. In a tree, any parent node
can have any number of child nodes. In a tree, all the nodes except root are child nodes.
6. Leaf
In a tree data structure, the node which does not have a child is called as LEAF Node. In simple words,
a leaf is a node with no child.
In a tree data structure, the leaf nodes are also called as External Nodes. External node is also a node
with no child. In a tree, leaf node is also called as 'Terminal' node.
7. Internal Nodes
In a tree data structure, the node which has atleast one child is called as INTERNAL Node. In simple
words, an internal node is a node with atleast one child.
In a tree data structure, nodes other than leaf nodes are called as Internal Nodes. The root node is
also said to be Internal Node if the tree has more than one node. Internal nodes are also called as
'Non-Terminal' nodes.
9. Level
In a tree data structure, the root node is said to be at Level 0 and the children of root node are at Level
1 and the children of the nodes which are at Level 1 will be at Level 2 and so on... In simple words, in a
tree each step from top to bottom is called as a Level and the Level count starts with '0' and
incremented by one at each level (Step).
10. Height
In a tree data structure, the total number of edges from leaf node to a particular node in the longest
path is called as HEIGHT of that Node. In a tree, height of the root node is said to be height of the
tree. In a tree, height of all leaf nodes is '0'.
12. Path
In a tree data structure, the sequence of Nodes and Edges from one node to another node is called
as PATH between that two Nodes. Length of a Path is total number of nodes in that path. In below
example the path A - B - E - J has length 4.
Binary Tree
Binary tree is a special tree data structure in which each node can have at most 2 children.
Thus, in a binary tree,
Each node has either 0 child or 1 child or 2 children.
Example-
A binary tree in which every node has either 0 or 2 children is called as a Full binary tree.
Full binary tree is also called as Strictly binary tree.
Example-
Here,
First binary tree is not a full binary tree.
This is because node C has only 1 child.
A complete binary tree is a binary tree that satisfies the following 2 properties-
Every internal node has exactly 2 children.
All the leaf nodes are at the same level.
Example-
A skewed binary tree is a binary tree that satisfies the following 2 properties-
All the nodes except one node (leaf node) has one and only one child.
The remaining node has no child.
OR
A skewed binary tree is a binary tree of n nodes such that its depth is (n-1).
Example-
A binary tree data structure is represented using two methods. Those methods are as follows...
1. Array Representation
In array representation we can assign numbers to all the nodes. Root node is assigned a no. 0 as
array starts from 0th position. A left child of root element is placed at (2d + 1) position where’d’ is
the position of parent element. A right child of root element is placed at (2d + 2) position.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
A B C D F G H I J - - - K - - - - - - - - -
To represent a binary tree of depth 'n' using array representation, we need one dimensional array with
a maximum size of 2n + 1.
Example:
struct node
{
int info;
struct node * left;
struct node * right;
} * root;
The above example of the binary tree represented using Linked list representation is shown as
follows...
A binary tree is said to be binary search tree when all nodes less than the root node are placed at the
left of root node and all nodes greater than or equal to the root node are placed at the right of root
node. The nodes in the binary search tree are ordered. The time needed to search an element from
the tree is reduced. Binary search tree also speed up the insertion and deletion operation.
Example
Expression tree
The expression tree is a binary tree in which each internal node corresponds to
the operator and each leaf node corresponds to the operand so for example
expression tree for 3 + ((5+9)*2) would be:
a + (b * c) + d * (e + f)
Q] Write algorithm for morder traversal for binary tree. Demonstrate with suitable example.
(**Note: Any Binary Tree Traversal shall be considered**) [W 16]
OR
Algorithm for Preorder Traversal:
Step 1: Visit root node.
Step 2: Visit left subtree in preorder.
Step 3: Visit right subtree in preorder.
Example:
Preorder traversal is: A, B, C.
In this traversal method 1st process root element then left subtree & then right subtree.
OR
Algorithm for Postorder Traversal:
Step 1: Visit left subtree in postorder.
Step 2: Visit right subtree in postorder.
Step 3: Visit root node
Example:
Q] Draw a binary search tree for given sequence and write postorder traversal of tree. [S-17]
10 5 8 9 7 6 2 15.
Q] Draw tree for given expression and find inorder, preorder and postorder traversal.
(a – 2b + 5c)2 (4d – 6e)5. 8 MARKS [S-17]