R24 Ads Unit-I
R24 Ads Unit-I
OR
Reusability The data structure provides reusability means that multiple client
programs can use the data structure.
Abstraction The data structure specified by an ADT also provides the level of
abstraction. The client cannot see the internal working of the data
structure, so it does not have to worry about the implementation part. The
client can only see the interface
Types of Data Structures
Non-Linear Data Structure: When one element is connected to the 'n' number of elements
known as a non-linear data structure. The best example is trees and graphs. In this case, the
elements are arranged in a random manner.
Static Representation of Data structures:
Stack Definition:
“A stack is a linear data structure. In which, insertions and deletions are takes place at one end,
called the top. Stack maintains a variable called top, which keeps track of the top most elements in
the stack”.
Stacks are sometimes called as Last-In-First-Out (LIFO) lists i.e. the element which is
inserted first in the stack, will be deleted last from the stack”
PUSH operation
POP operation:
Top and its value
Push operation
Algorithm:
1. begin
2. if top = n then stack full
3. top = top + 1
4. stack (top) : = item;
5. end
Pop operation
Algorithm:
1. begin
2. if top = 0 then stack empty;
3. item := stack(top);
4. top = top - 1;
5. end;
Peek operation
Algorithm:
PEEK (STACK, TOP)
1. Begin
2. if top = -1 then stack empty
3. item = stack[top]
4. return item
5. End
isEmpty Operation
Returns true if the stack is empty, else false.
Algorithm for isEmpty Operation:
1. Check for the value of top in stack.
2. If (top == -1), then the stack is empty so return true .
3. Otherwise, the stack is not empty so return false .
isFull Operation
Returns true if the stack is full, else false.
Algorithm for isFull Operation:
1. Check for the value of top in stack.
2. If (top == capacity-1), then the stack is full so return true.
3. Otherwise, the stack is not full so return false.
Applications of stacks:
Expression Evaluations & Conversions: A stack is a very effective data structure for evaluating arithmetic
expressions in programming languages. An arithmetic expression consists of operands and operators.
Backtracking(Recursion): Backtracking is another application of Stack. It is a recursive algorithm that is used
for solving the optimization problem.
Parsing (Delimiter Checking) : The common application of Stack is delimiter checking, i.e., parsing that
involves analyzing a source program syntactically. It is also called parenthesis checking.
Function calls: Stacks are used to keep track of the return addresses of function calls, allowing the program to
return to the correct location after a function has finished executing.
Editors: Undo and Redo functions in any text editor.
Tree Traversals: Stacks are useful for Depth First Search Traversal method.
Browsers: Stacks are useful for function calls, storing the activation records. The history of a web browser is
stored in the form of a stack.
Evaluation of expression.
Expression Types:
Based on the operator position, expressions are divided into THREE types. They are as follows...
1. Infix Expression
2. Postfix Expression
3. Prefix Expression
Infix Expression:
Postfix Expression:
Prefix Expression:
Order of Operations (Precedence) from left to right
P.Archana 22
Evaluation of Postfix Expression using Stack:
Algorithm:
Step-1: Create an empty STACK and start scanning the Postfix expression from
Left to Right.
Step-2: if the element is an Operand, PUSH it into the STACK.
Step-3: if the element is an Operator, POP twice and get top most two elements
A and B; Calculate B Operator A and PUSH the result back into the STACK.
Step-4: When the expression is ended, the value in the STACK is the final
answer.
Example:01
ii) 2 + 3 * 4 – 5 => 2 + (3 4 *) -
i)4 + 6 * 2 = > 4 + (6 2 *)
5
= ( 4 6 2 * +)
= (2 3 4 * +) – 5
=462*+
= (2 3 4 5 * + -)
=234*+5–
iii)2 * 6 /2 – 3 + 7 => (2 6 *) / 2 – 3 + 7
=(26*2/)–3+7
= (2 6 * 2 / 3 -) + 7
= (2 6 * 2 / 3 - 7 +)
=26*2/3–7+
Conversion of Infix to Prefix Expression
using Stack
Algorithm
Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more than one rings
is as depicted.
These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller one sits over
the larger one.
There are other variations of the puzzle where the number of disks increase, but the tower count
remains the same
Rules:
The mission is to move all the disks to some another tower without violating the sequence of arrangement. A
few rules to be followed for Tower of Hanoi are
Only one disk can be moved at a time.
Each move consists of taking the upper disk from one of the stacks and placing it on top of another
stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
No disk may be placed on top of a smaller disk.
27
Example: Input: N = 3,
Step 1 − Move N-1 disks from A to B, using C.
Step 2 − Move Last (Nth) disk from A to C.
Step 3 − Move N-1 disks from B to C, using A
28
A recursive algorithm
START
Procedure Hanoi(disk, source, dest, aux)
IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF
END Procedure
STOP
Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps. This presentation shows
that a puzzle with 3 disks has taken 23 - 1 = 7 steps
29
Parenthesis checker
Example 1: 2 * ( ( 4/2 ) + 5 )
The above expression has two opening and two closing brackets which means that the above expression is a
balanced parenthesis.
Example 2: 2 * ( ( 4/2 ) + 5
The above expression has two opening brackets and one closing bracket, which means that both opening and
closing brackets are not equal; therefore, the above expression is unbalanced
30
// Main function
// Function to check if the expression is balanced int main() {
int isBalanced(char* text) { char text[MAX_SIZE];
int i; printf("Input an expression in parentheses: ");
for (i = 0; i < strlen(text); i++) { scanf("%s", text);
if (text[i] == '(' || text[i] == '[' || text[i] == '{') {
push(text[i]); // Check if the expression is balanced or not
} else if (text[i] == ')' || text[i] == ']' || text[i] == '}') { if (isBalanced(text)) {
if (top == -1) { printf("The expression is balanced.\n");
return 0; // If no opening bracket is present } else {
} else if (!is_matching_pair(pop(), text[i])) { printf("The expression is not balanced.\n");
return 0; // If closing bracket doesn't match }
the last opening bracket return 0;
}}} }
if (top == -1) {
return 1; // If the stack is empty, the expression is balanced
} else { Input an expression in parentheses: (([{}]))
return 0; // If the stack is not empty, the expression is not balanced The expression is balanced.
}}
31
TREES
Tree is a non-linear data structure which organizes data in hierarchical structure and this is a recursive
definition.
A tree is a finite set of nodes together with a finite set of directed edges (links/branches) that define parent-child
(HIERARCHICAL) relationships
Example:
32
A tree satisfies the following properties:
It has one designated node, called the root that has no parent.
33
Terminology
1. Root: Root:
2. Parent:
3. Edge:
4. Child:
5. Degree:
6. Internal Nodes:
7. Leaf:
8. Siblings:
9. Level:
10. Height:
11. Depth:
12. Path:
13. Sub Tree:
34
BINARY TREE
A tree in which every node can have a maximum of two children is called Binary Tree
35
Different types of binary trees
A binary tree in which every node has either two or zero number of children is called Strictly
Binary Tree
Strictly binary tree is also called as Full Binary Tree or Proper Binary Tree or 2-Tree
36
2. Complete Binary Tree:
A complete binary tree is a binary tree in which every level is completely filled except possibly the last level. In
the unfilled level, the nodes are attached starting from the left-most position
37
3. Extended Binary Tree:
The full binary tree obtained by adding dummy nodes to a binary tree is called as Extended Binary Tree
38
4. Degenerate Binary Tree:
The degenerate binary tree is a tree in which all the internal nodes have only one children.
Let's understand the Degenerate binary tree through examples.
right-skewed left-skewed
39
Binary Tree Representations
A binary tree data structure is represented using two methods. Those methods are as follows...
a) Array Representation
b) Linked List Representation
40
Representation of Binary Trees using Arrays
The sequential representation uses an array for the storage of tree elements (nodes).
The number of nodes a binary tree has defines the size of the array being used.
The ROOT node of the binary tree lies at the array’s first index.
The index at which a particular node is stored will define the indices at which the right and left
children of the node will be stored. An empty tree has NULL or ZERO as its first index
41
Height of the given Binary Tree,h = 2
1 2 3 4 5 6 7
A B C D E F G
42
Height of the given Binary Tree,h = 2
1 2 3 4 5 6 7
A B C D --- ---- G
- -
43
Advantages:
Static data storage: Direct access to any node is possible due its static memory allocation.
Random Access: To find the parent, left child or right child of any particular node is fast because of
random access.
Disadvantages:
Memory Wastage: wastage of memory due to its memory allocation for missing elements.
Implementation: It depends on height of the tree and as well as total nodes of the tree.
Insertion and Deletion operation: The insertion and deletion of any node in the tree will be
costlier (difficult) as other nodes have to be adjusted at appropriate positions
44
Representation of Binary Trees using Linked List
45
Example:1
The above example of the binary tree represented using Linked list representation is shown as follows...
46
Example-2:
The above example of the binary tree represented using Linked list representation is shown as follows
47
Advantages:
Dynamic data storage: it can grow and shrink at runtime by allocating and deallocating memory.
No Memory Wastage: Efficient memory utilization can be achieved since the size of the linked list increase
or decrease at runtime.
Insertion and Deletion operation: Insertion and deletion operations are quite easier in the linked list.
There is no need to shift elements after the insertion or deletion of an element only the address present in
the next pointer needs to be update.
Disadvantages:
Memory Usage: Extra memory is required in the linked list as compared to an array. Because in a linked
list, a pointer is also required to store the address of the next element and it require extra memory for
itself.
Traversal: Direct or random accessing to an element is not possible in a linked list due to its dynamic
48
memory allocation. That means extra memory is used for pointers with every element
Binary Tree Traversal
Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree Traversal
49
In-order Traversal: (left Child - root - right Child)
Algorithm:
Example-1:
We start from A, and following in-order traversal.
We move to its left sub-tree first; that is B.
B is also traversed in-order.
The process goes on until all nodes are visited.
The In-order traversal of the above binary tree is
DàBàEàAàFàCàG 50
Example-2:
We start from 23, and following in-order traversal.
We move to its left sub-tree first; that is 4.
4 is also traversed in-order.
The process goes on until all nodes are visited.
The In-order traversal of the above binary tree is
1 à 4 à 7 à 11 à 20 à 23 à 24 à 30 à 34
51
2. Pre - Order Traversal (root – left Child – right Child):
Algorithm:
Example-1:
èWe start from A, and following pre-order traversal.
è We move to its left sub-tree first; that is B.
è B is also traversed pre-order.
è The process goes on until all nodes are visited.
The pre-order traversal of the above binary tree is
Aà B à Dà Eà Cà Fà G
52
Example-2:
è We start from 23, and following pre-order traversal
è We move to its left sub-tree first; that is 4.
è 4 is also traversed pre-order.
è The process goes on until all nodes are visited
The pre-order traversal of the above binary tree is
23à 4 à 1à 11 à 7à 20à 30à24à 34
53
Post - Order Traversal (left Child – right Child - root
Algorithm:
Example-1:
è We start from A, and following post-order traversal.
è We move to its left sub-tree first; that is B.
è B is also traversed post-order.
è The process goes on until all nodes are visited.
The post-order traversal of the above binary tree is
Dà Eà Bà Fà Gà Cà A
54
Example-2:
èWe start from 23, and following post-order
traversal.
è We move to its left sub-tree first; that is 4.
è 4 is also traversed post-order.
è The process goes on until all nodes are visited.
The post-order traversal of the above binary tree is
1à 7à 20à 11 à4à 24à 34à30à 23
55
Construct a Binary Tree using In-order and Post-order Tree traversals
Algorithm:
56
Example-1: To Construct a binary tree using the following In-order and
Post-order traversal of the binary tree:
Example-2: To Construct a binary tree using the following In-order and Post-order traversals of the binary tree:
57
Construct a Binary Tree using In-order and Pre-order Tree traversals
Algorithm:
1. Find the root node using the pre-order traversal.
2. Find the left sub trees and the right sub trees using in-order traversal by finding the index of the root node of
respective sub trees.
3. Once the root node is found, we can recurse down on the left and right sub trees, i.e., left sub array, and right
sub array split at respective root index to repeat the same process until we find at most a single element in
either sub-array
58
Example-1: Construct binary tree for given preorder and in order traversals.
In order: 2-3-4-5-6-8-10
Preorder: 5-3-2-4-8-6-10
In order
2-3-4 ← 5 → 6-8-10
59
Example:2: Construct binary tree for given post order and in
order traversals.
Example:3 Construct binary tree for given post order and in order traversals.
60