SlideShare a Scribd company logo
Introduction to Data Structures
Presented By:Presented By:
Anil DuttAnil Dutt
DataStructures
• Outline
• Introduction
• Linked Lists
• Stacks
• Queues
• Trees
• Graphs
Introduction
• Dynamic data structures
– Data structures that grow and shrink during execution
• Linked lists
– Allow insertions and removals anywhere
• Stacks
– Allow insertions and removals only at top of stack
• Queues
– Allow insertions at the back and removals from the front
• Binary trees
– High-speed searching and sorting of data and efficient
elimination of duplicate data items
Linked Lists
• Linked list
– Linear collection of self-referential class objects, called nodes
– Connected by pointer links
– Accessed via a pointer to the first node of the list
– Subsequent nodes are accessed via the link-pointer member of
the current node
– Link pointer in the last node is set to null to mark the list’s end
• Use a linked list instead of an array when
– You have an unpredictable number of data elements
– Your list needs to be sorted quickly
Linked Lists
• Types of linked lists:
– Singly linked list
• Begins with a pointer to the first node
• Terminates with a null pointer
• Only traversed in one direction
– Circular, singly linked
• Pointer in the last node points back to the first node
– Doubly linked list
• Two “start pointers” – first element and last element
• Each node has a forward pointer and a backward pointer
• Allows traversals both forwards and backwards
– Circular, doubly linked list
• Forward pointer of the last node points to the first node and
backward pointer of the first node points to the last node
SINGLY LINKED LIST
DOUBLY LINKED LIST
Previous node Data part Next node
DATA ADDRESS
Data 1 Data 2 . . . . . . Data n ADDRESS
ADDRESS
Data 1 Data 2 . . . . . Data
n
ADDRESS
ID Name Desig Address
of Node2
ID Name Desig Address of
Node 3
ID Name Desig NULL
Start
NULL Data 1 Address of
Node 2
Address of Data 2 Address of
Node 1 Node 3
Address of Data 3
Node 2 NULL
Start
CIRCULAR LINKED LIST
SINGLY
Node 1 Node 2 Node 3
DOUBLY
Node 1 Node 2
Node 3
Start
Data 1 Node 2 Data 2 Node 3 Data 3 Node1
Start
Node3 Data 1 Node 2 Node 1 Data 1 Node 3
Node 2 Data 1 Node1
struct node
{
int x;
char c[10];
struct node *next;
}*current;
x c[10] next
create_node()
{
current=(struct node *)malloc(sizeof(struct node));
current->x=10; current->c=“try”; current->next=null;
return current;
}
Allocation
Assignment
x c[10] next
10 try NULL
Create a linked list for maintaining the employee
details such as Ename,Eid,Edesig.
Steps:
1)Identify the node structure
2)Allocate space for the node
3)Insert the node in the list
EID EName EDesig
struct node
{
int Eid;
char Ename[10],Edesig[10];
struct node *next;
} *current;
next
The basic operations on linked lists are
1. Creation
2. Insertion
3. Deletion
4. Traversing
5. Searching
6. Concatenation
7. Display
Stacks
• Stack
– New nodes can be added and removed only at the top
– Similar to a pile of dishes
– Last-in, first-out (LIFO)
– Bottom of stack indicated by a link member to NULL
– Constrained version of a linked list
• push
– Adds a new node to the top of the stack
• pop
– Removes a node from the top
– Stores the popped value
– Returns true if pop was successful
Stack
A
X
R
C
push(M)
A
X
R
C
M
item = pop()
item = M
A
X
R
C
Implementing a Stack
• At least three different ways to implement
a stack
– array
– vector
– linked list
• Which method to use depends on the
application
– what advantages and disadvantages does
each implementation have?
Queues
• Queue
– Similar to a supermarket checkout line
– First-in, first-out (FIFO)
– Nodes are removed only from the head
– Nodes are inserted only at the tail
• Insert and remove operations
– Enqueue (insert) and dequeue (remove)
Queues 18
A QUEUE IS A CONTAINER IN WHICH:
. INSERTIONS ARE MADE ONLY AT
THE BACK;
. DELETIONS, RETRIEVALS, AND
MODIFICATIONS ARE MADE ONLY
AT THE FRONT.
Queues 19
The Queue
A Queue is a FIFO (First in
First Out) Data Structure.
Elements are inserted in
the Rear of the queue and
are removed at the Front.
C
B C
A B C
A
b a c k
f r o n t
p u s h A
A B
f r o n t b a c k
p u s h B
f r o n t b a c k
p u s h C
f r o n t b a c k
p o p A
f r o n t
b a c k
p o p B
Queues 20
PUSH (ALSO CALLED ENQUEUE) -- TO
INSERT AN ITEM AT THE BACK
POP (ALSO CALLED DEQUEUE) -- TO
DELETE THE FRONT ITEM
IN A QUEUE, THE FIRST ITEM
INSERTED WILL BE THE FIRST ITEM
DELETED: FIFO (FIRST-IN, FIRST-OUT)
21
Printing Queue
Now printing A.doc
A.doc is finished. Now printing B.doc
Now still printing B.docD.doc comes
• A.doc B.doc C.doc arrive to printer.
ABC
BC
BCD
CD
D
B.doc is finished. Now printing C.doc
C.doc is finished. Now printing D.doc
Trees
• Tree nodes contain two or more links
– All other data structures we have discussed only contain one
• Binary trees
– All nodes contain two links
• None, one, or both of which may be NULL
– The root node is the first node in a tree.
– Each link in the root node refers to a child
– A node with no children is called a leaf node
Trees
• Diagram of a binary tree
B
A D
C
Trees
• Binary search tree
– Values in left subtree less than parent
– Values in right subtree greater than parent
– Facilitates duplicate elimination
– Fast searches - for a balanced tree, maximum of log n
comparisons
47
25 77
11 43 65 93
687 17 31 44
2
Trees
• Tree traversals:
– Inorder traversal – prints the node values in ascending order
1. Traverse the left subtree with an inorder traversal
2. Process the value in the node (i.e., print the node value)
3. Traverse the right subtree with an inorder traversal
– Preorder traversal
1. Process the value in the node
2. Traverse the left subtree with a preorder traversal
3. Traverse the right subtree with a preorder traversal
– Postorder traversal
1. Traverse the left subtree with a postorder traversal
2. Traverse the right subtree with a postorder traversal
3. Process the value in the node
Trees Data Structures
 Tree
 Nodes
 Each node can have 0 or more children
 A node can have at most one parent
 Binary tree
 Tree with 0–2 children per node
Tree Binary Tree
Trees
 Terminology
 Root ⇒ no parent
 Leaf ⇒ no child
 Interior ⇒ non-leaf
 Height ⇒ distance from root to leaf
Root node
Leaf nodes
Interior nodes Height
Binary Search Trees
 Key property
 Value at node
 Smaller values in left subtree
 Larger values in right subtree
 Example
 X > Y
 X < Z
Y
X
Z
Binary Search Trees
 Examples
Binary
search trees
Not a binary
search tree
5
10
30
2 25 45
5
10
45
2 25 30
5
10
30
2
25
45
Binary Tree Implementation
Class Node {
int data; // Could be int, a class, etc
Node *left, *right; // null if empty
void insert ( int data ) { … }
void delete ( int data ) { … }
Node *find ( int data ) { … }
…
}
Iterative Search of Binary Tree
Node *Find( Node *n, int key) {
while (n != NULL) {
if (n->data == key) // Found it
return n;
if (n->data > key) // In left subtree
n = n->left;
else // In right subtree
n = n->right;
}
return null;
}
Node * n = Find( root, 5);
Recursive Search of Binary Tree
Node *Find( Node *n, int key) {
if (n == NULL) // Not found
return( n );
else if (n->data == key) // Found it
return( n );
else if (n->data > key) // In left subtree
return Find( n->left, key );
else // In right subtree
return Find( n->right, key );
}
Node * n = Find( root, 5);
Example Binary Searches
 Find ( root, 2 )
5
10
30
2 25 45
5
10
30
2
25
45
10 > 2, left
5 > 2, left
2 = 2, found
5 > 2, left
2 = 2, found
root
Example Binary Searches
 Find (root, 25 )
5
10
30
2 25 45
5
10
30
2
25
45
10 < 25, right
30 > 25, left
25 = 25, found
5 < 25, right
45 > 25, left
30 > 25, left
10 < 25, right
25 = 25, found
Types of Binary Trees
 Degenerate – only one child
 Complete – always two children
 Balanced – “mostly” two children
 more formal definitions exist, above are intuitive ideas
Degenerate
binary tree
Balanced
binary tree
Complete
binary tree
Binary Trees Properties
 Degenerate
 Height = O(n) for n
nodes
 Similar to linked list
 Balanced
 Height = O( log(n) )
for n nodes
 Useful for searches
Degenerate
binary tree
Balanced
binary tree
Binary Search Properties
 Time of search
 Proportional to height of tree
 Balanced binary tree
 O( log(n) ) time
 Degenerate tree
 O( n ) time
 Like searching linked list / unsorted array
Binary Search Tree Construction
 How to build & maintain binary trees?
 Insertion
 Deletion
 Maintain key property (invariant)
 Smaller values in left subtree
 Larger values in right subtree
Binary Search Tree – Insertion
 Algorithm
1. Perform search for value X
2. Search will end at node Y (if X not in tree)
3. If X < Y, insert new leaf X as new left subtree for
Y
4. If X > Y, insert new leaf X as new right subtree
for Y
 Observations
 O( log(n) ) operation for balanced tree
 Insertions may unbalance tree
Example Insertion
 Insert ( 20 )
5
10
30
2 25 45
10 < 20, right
30 > 20, left
25 > 20, left
Insert 20 on left
20
Binary Search Tree – Deletion
 Algorithm
1. Perform search for value X
2. If X is a leaf, delete X
3. Else // must delete internal node
a) Replace with largest value Y on left subtree
OR smallest value Z on right subtree
b) Delete replacement value (Y or Z) from subtree
Observation
 O( log(n) ) operation for balanced tree
 Deletions may unbalance tree
Example Deletion (Leaf)
 Delete ( 25 )
5
10
30
2 25 45
10 < 25, right
30 > 25, left
25 = 25, delete
5
10
30
2 45
Example Deletion (Internal Node)
 Delete ( 10 )
5
10
30
2 25 45
5
5
30
2 25 45
2
5
30
2 25 45
Replacing 10
with largest
value in left
subtree
Replacing 5
with largest
value in left
subtree
Deleting leaf
Example Deletion (Internal Node)
 Delete ( 10 )
5
10
30
2 25 45
5
25
30
2 25 45
5
25
30
2 45
Replacing 10
with smallest
value in right
subtree
Deleting leaf Resulting tree
Balanced Search Trees
 Kinds of balanced binary search trees
 height balanced vs. weight balanced
 “Tree rotations” used to maintain balance on insert/delete
 Non-binary search trees
 2/3 trees
 each internal node has 2 or 3 children
 all leaves at same depth (height balanced)
 B-trees
 Generalization of 2/3 trees
 Each internal node has between k/2 and k children
 Each node has an array of pointers to children
 Widely used in databases
Other (Non-Search) Trees
 Parse trees
 Convert from textual representation to tree
representation
 Textual program to tree
 Used extensively in compilers
 Tree representation of data
 E.g. HTML data can be represented as a tree
 called DOM (Document Object Model) tree
 XML
 Like HTML, but used to represent data
 Tree structured
Parse Trees
 Expressions, programs, etc can be
represented by tree structures
 E.g. Arithmetic Expression Tree
 A-(C/5 * 2) + (D*5 % 4)
+
- %
A * * 4
/ 2 D 5
C 5
Tree Traversal
 Goal: visit every node of a tree
 in-order traversal
void Node::inOrder () {
if (left != NULL) {
cout << “(“; left->inOrder(); cout << “)”;
}
cout << data << endl;
if (right != NULL) right->inOrder()
}Output: A – C / 5 * 2 + D * 5 % 4
To disambiguate: print brackets
+
- %
A * * 4
/ 2 D 5
C 5
Tree Traversal (contd.)
 pre-order and post-order:
void Node::preOrder () {
cout << data << endl;
if (left != NULL) left->preOrder ();
if (right != NULL) right->preOrder ();
}
void Node::postOrder () {
if (left != NULL) left->preOrder ();
if (right != NULL) right->preOrder ();
cout << data << endl;
}
Output: + - A * / C 5 2 % * D 5 4
Output: A C 5 / 2 * - D 5 * 4 % +
+
- %
A * * 4
/ 2 D 5
C 5
Graph Data Structures
 E.g: Airline networks, road networks, electrical circuits
 Nodes and Edges
 E.g. representation: class Node
 Stores name
 stores pointers to all adjacent nodes
 i,e. edge == pointer
 To store multiple pointers: use array or linked list
Ahm’bad
Delhi
Mumbai
Calcutta
Chennai
Madurai

More Related Content

PDF
Introduction to data structure
PPTX
DATA STRUCTURE IN C LANGUAGE
PPTX
DATA STRUCTURE
PDF
Data structures (introduction)
PDF
Data structure ppt
PPT
Data structure lecture 1
PPTX
Data structure & its types
Introduction to data structure
DATA STRUCTURE IN C LANGUAGE
DATA STRUCTURE
Data structures (introduction)
Data structure ppt
Data structure lecture 1
Data structure & its types

What's hot (20)

PPTX
Data structure,abstraction,abstract data type,static and dynamic,time and spa...
PPT
Data structures
PDF
Data Structure Basics
PDF
Data Structures Notes 2021
PPTX
Bca ii dfs u-1 introduction to data structure
PPTX
Introduction To Data Structures.
PPTX
Introduction to data structure ppt
PDF
Data Structures
PPT
Data structures using c
PDF
Data structures
PDF
Datastructure
PDF
Data structure
PPTX
Introduction to data structure
PPT
Data structures using C
PDF
Data structure using c++
PPTX
Data structure and its types
PPTX
Data structures
PDF
Introduction to Data Structure
PPTX
Data structure power point presentation
PPTX
Introduction to data_structure
Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structures
Data Structure Basics
Data Structures Notes 2021
Bca ii dfs u-1 introduction to data structure
Introduction To Data Structures.
Introduction to data structure ppt
Data Structures
Data structures using c
Data structures
Datastructure
Data structure
Introduction to data structure
Data structures using C
Data structure using c++
Data structure and its types
Data structures
Introduction to Data Structure
Data structure power point presentation
Introduction to data_structure
Ad

Viewers also liked (20)

PDF
linked list
PDF
01 05 - introduction xml
PPT
L6 structure
PPTX
Method overloading
PPTX
‫Chapter3 inheritance
PPTX
5 Array List, data structure course
PDF
3 Array operations
PDF
Data Structure (Introduction to Data Structure)
PPTX
PPTX
Mca ii dfs u-1 introduction to data structure
PDF
Topological Sort
PPTX
Trees data structure
PPTX
Graphs data Structure
PPT
Basic data-structures-v.1.1
PPTX
Data structure &amp; algorithms introduction
PDF
data structure and algorithms
PPTX
‫‫Chapter4 Polymorphism
PPTX
2 introduction to data structure
PPTX
Data Structures
PPTX
TYPES DATA STRUCTURES( LINEAR AND NON LINEAR)....
linked list
01 05 - introduction xml
L6 structure
Method overloading
‫Chapter3 inheritance
5 Array List, data structure course
3 Array operations
Data Structure (Introduction to Data Structure)
Mca ii dfs u-1 introduction to data structure
Topological Sort
Trees data structure
Graphs data Structure
Basic data-structures-v.1.1
Data structure &amp; algorithms introduction
data structure and algorithms
‫‫Chapter4 Polymorphism
2 introduction to data structure
Data Structures
TYPES DATA STRUCTURES( LINEAR AND NON LINEAR)....
Ad

Similar to Introduction to data structure by anil dutt (20)

PPTX
UNIT 2 TREES & GRAPH COMPLETE NOTES OF DATA STRUCTURE
PDF
Data Structure Lecture 3 Linked Lists.pdf
PPT
Fundamentalsofdatastructures 110501104205-phpapp02
PPTX
Binary tree
PPTX
BST.pptx this isp used for learning binary search trees
PPTX
BST.pptx this is Good for data structure
PPT
bst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
PPTX
presentation 1 binary search tree in data structures.pptx
PPTX
Lecture 4 data structures and algorithms
PPT
Binary Search Tree
PPTX
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
PPTX
3.linked list
PDF
CS-102 BST_27_3_14v2.pdf
PDF
CS-102 BST_27_3_14.pdf
PDF
Unit iv data structure-converted
PPTX
UNIT 2LINKEDLISdddddddddddddddddddddddddddT.pptx
PPT
Fundamentals of data structures
PPTX
8.binry search tree
PPTX
Data Strcutres-Non Linear DS-Advanced Trees
PPT
BINARY SEARCH TREE
UNIT 2 TREES & GRAPH COMPLETE NOTES OF DATA STRUCTURE
Data Structure Lecture 3 Linked Lists.pdf
Fundamentalsofdatastructures 110501104205-phpapp02
Binary tree
BST.pptx this isp used for learning binary search trees
BST.pptx this is Good for data structure
bst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
presentation 1 binary search tree in data structures.pptx
Lecture 4 data structures and algorithms
Binary Search Tree
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
3.linked list
CS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14.pdf
Unit iv data structure-converted
UNIT 2LINKEDLISdddddddddddddddddddddddddddT.pptx
Fundamentals of data structures
8.binry search tree
Data Strcutres-Non Linear DS-Advanced Trees
BINARY SEARCH TREE

More from Anil Dutt (6)

PPTX
Sorting techniques Anil Dutt
PPT
File handling-dutt
PPTX
Ponters
PDF
Control statements anil
PPTX
Array
PPTX
Structure of c_program_to_input_output
Sorting techniques Anil Dutt
File handling-dutt
Ponters
Control statements anil
Array
Structure of c_program_to_input_output

Recently uploaded (20)

PPTX
Construction Project Organization Group 2.pptx
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
DOCX
573137875-Attendance-Management-System-original
PPTX
additive manufacturing of ss316l using mig welding
PDF
Well-logging-methods_new................
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
Sustainable Sites - Green Building Construction
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
Welding lecture in detail for understanding
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PDF
composite construction of structures.pdf
PPTX
Geodesy 1.pptx...............................................
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
Internet of Things (IOT) - A guide to understanding
Construction Project Organization Group 2.pptx
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Model Code of Practice - Construction Work - 21102022 .pdf
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Lesson 3_Tessellation.pptx finite Mathematics
573137875-Attendance-Management-System-original
additive manufacturing of ss316l using mig welding
Well-logging-methods_new................
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Sustainable Sites - Green Building Construction
Embodied AI: Ushering in the Next Era of Intelligent Systems
Welding lecture in detail for understanding
Arduino robotics embedded978-1-4302-3184-4.pdf
composite construction of structures.pdf
Geodesy 1.pptx...............................................
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
OOP with Java - Java Introduction (Basics)
Internet of Things (IOT) - A guide to understanding

Introduction to data structure by anil dutt

  • 1. Introduction to Data Structures Presented By:Presented By: Anil DuttAnil Dutt
  • 2. DataStructures • Outline • Introduction • Linked Lists • Stacks • Queues • Trees • Graphs
  • 3. Introduction • Dynamic data structures – Data structures that grow and shrink during execution • Linked lists – Allow insertions and removals anywhere • Stacks – Allow insertions and removals only at top of stack • Queues – Allow insertions at the back and removals from the front • Binary trees – High-speed searching and sorting of data and efficient elimination of duplicate data items
  • 4. Linked Lists • Linked list – Linear collection of self-referential class objects, called nodes – Connected by pointer links – Accessed via a pointer to the first node of the list – Subsequent nodes are accessed via the link-pointer member of the current node – Link pointer in the last node is set to null to mark the list’s end • Use a linked list instead of an array when – You have an unpredictable number of data elements – Your list needs to be sorted quickly
  • 5. Linked Lists • Types of linked lists: – Singly linked list • Begins with a pointer to the first node • Terminates with a null pointer • Only traversed in one direction – Circular, singly linked • Pointer in the last node points back to the first node – Doubly linked list • Two “start pointers” – first element and last element • Each node has a forward pointer and a backward pointer • Allows traversals both forwards and backwards – Circular, doubly linked list • Forward pointer of the last node points to the first node and backward pointer of the first node points to the last node
  • 6. SINGLY LINKED LIST DOUBLY LINKED LIST Previous node Data part Next node DATA ADDRESS Data 1 Data 2 . . . . . . Data n ADDRESS ADDRESS Data 1 Data 2 . . . . . Data n ADDRESS
  • 7. ID Name Desig Address of Node2 ID Name Desig Address of Node 3 ID Name Desig NULL Start
  • 8. NULL Data 1 Address of Node 2 Address of Data 2 Address of Node 1 Node 3 Address of Data 3 Node 2 NULL Start
  • 9. CIRCULAR LINKED LIST SINGLY Node 1 Node 2 Node 3 DOUBLY Node 1 Node 2 Node 3 Start Data 1 Node 2 Data 2 Node 3 Data 3 Node1 Start Node3 Data 1 Node 2 Node 1 Data 1 Node 3 Node 2 Data 1 Node1
  • 10. struct node { int x; char c[10]; struct node *next; }*current; x c[10] next
  • 11. create_node() { current=(struct node *)malloc(sizeof(struct node)); current->x=10; current->c=“try”; current->next=null; return current; } Allocation Assignment x c[10] next 10 try NULL
  • 12. Create a linked list for maintaining the employee details such as Ename,Eid,Edesig. Steps: 1)Identify the node structure 2)Allocate space for the node 3)Insert the node in the list EID EName EDesig struct node { int Eid; char Ename[10],Edesig[10]; struct node *next; } *current; next
  • 13. The basic operations on linked lists are 1. Creation 2. Insertion 3. Deletion 4. Traversing 5. Searching 6. Concatenation 7. Display
  • 14. Stacks • Stack – New nodes can be added and removed only at the top – Similar to a pile of dishes – Last-in, first-out (LIFO) – Bottom of stack indicated by a link member to NULL – Constrained version of a linked list • push – Adds a new node to the top of the stack • pop – Removes a node from the top – Stores the popped value – Returns true if pop was successful
  • 16. Implementing a Stack • At least three different ways to implement a stack – array – vector – linked list • Which method to use depends on the application – what advantages and disadvantages does each implementation have?
  • 17. Queues • Queue – Similar to a supermarket checkout line – First-in, first-out (FIFO) – Nodes are removed only from the head – Nodes are inserted only at the tail • Insert and remove operations – Enqueue (insert) and dequeue (remove)
  • 18. Queues 18 A QUEUE IS A CONTAINER IN WHICH: . INSERTIONS ARE MADE ONLY AT THE BACK; . DELETIONS, RETRIEVALS, AND MODIFICATIONS ARE MADE ONLY AT THE FRONT.
  • 19. Queues 19 The Queue A Queue is a FIFO (First in First Out) Data Structure. Elements are inserted in the Rear of the queue and are removed at the Front. C B C A B C A b a c k f r o n t p u s h A A B f r o n t b a c k p u s h B f r o n t b a c k p u s h C f r o n t b a c k p o p A f r o n t b a c k p o p B
  • 20. Queues 20 PUSH (ALSO CALLED ENQUEUE) -- TO INSERT AN ITEM AT THE BACK POP (ALSO CALLED DEQUEUE) -- TO DELETE THE FRONT ITEM IN A QUEUE, THE FIRST ITEM INSERTED WILL BE THE FIRST ITEM DELETED: FIFO (FIRST-IN, FIRST-OUT)
  • 21. 21 Printing Queue Now printing A.doc A.doc is finished. Now printing B.doc Now still printing B.docD.doc comes • A.doc B.doc C.doc arrive to printer. ABC BC BCD CD D B.doc is finished. Now printing C.doc C.doc is finished. Now printing D.doc
  • 22. Trees • Tree nodes contain two or more links – All other data structures we have discussed only contain one • Binary trees – All nodes contain two links • None, one, or both of which may be NULL – The root node is the first node in a tree. – Each link in the root node refers to a child – A node with no children is called a leaf node
  • 23. Trees • Diagram of a binary tree B A D C
  • 24. Trees • Binary search tree – Values in left subtree less than parent – Values in right subtree greater than parent – Facilitates duplicate elimination – Fast searches - for a balanced tree, maximum of log n comparisons 47 25 77 11 43 65 93 687 17 31 44 2
  • 25. Trees • Tree traversals: – Inorder traversal – prints the node values in ascending order 1. Traverse the left subtree with an inorder traversal 2. Process the value in the node (i.e., print the node value) 3. Traverse the right subtree with an inorder traversal – Preorder traversal 1. Process the value in the node 2. Traverse the left subtree with a preorder traversal 3. Traverse the right subtree with a preorder traversal – Postorder traversal 1. Traverse the left subtree with a postorder traversal 2. Traverse the right subtree with a postorder traversal 3. Process the value in the node
  • 26. Trees Data Structures  Tree  Nodes  Each node can have 0 or more children  A node can have at most one parent  Binary tree  Tree with 0–2 children per node Tree Binary Tree
  • 27. Trees  Terminology  Root ⇒ no parent  Leaf ⇒ no child  Interior ⇒ non-leaf  Height ⇒ distance from root to leaf Root node Leaf nodes Interior nodes Height
  • 28. Binary Search Trees  Key property  Value at node  Smaller values in left subtree  Larger values in right subtree  Example  X > Y  X < Z Y X Z
  • 29. Binary Search Trees  Examples Binary search trees Not a binary search tree 5 10 30 2 25 45 5 10 45 2 25 30 5 10 30 2 25 45
  • 30. Binary Tree Implementation Class Node { int data; // Could be int, a class, etc Node *left, *right; // null if empty void insert ( int data ) { … } void delete ( int data ) { … } Node *find ( int data ) { … } … }
  • 31. Iterative Search of Binary Tree Node *Find( Node *n, int key) { while (n != NULL) { if (n->data == key) // Found it return n; if (n->data > key) // In left subtree n = n->left; else // In right subtree n = n->right; } return null; } Node * n = Find( root, 5);
  • 32. Recursive Search of Binary Tree Node *Find( Node *n, int key) { if (n == NULL) // Not found return( n ); else if (n->data == key) // Found it return( n ); else if (n->data > key) // In left subtree return Find( n->left, key ); else // In right subtree return Find( n->right, key ); } Node * n = Find( root, 5);
  • 33. Example Binary Searches  Find ( root, 2 ) 5 10 30 2 25 45 5 10 30 2 25 45 10 > 2, left 5 > 2, left 2 = 2, found 5 > 2, left 2 = 2, found root
  • 34. Example Binary Searches  Find (root, 25 ) 5 10 30 2 25 45 5 10 30 2 25 45 10 < 25, right 30 > 25, left 25 = 25, found 5 < 25, right 45 > 25, left 30 > 25, left 10 < 25, right 25 = 25, found
  • 35. Types of Binary Trees  Degenerate – only one child  Complete – always two children  Balanced – “mostly” two children  more formal definitions exist, above are intuitive ideas Degenerate binary tree Balanced binary tree Complete binary tree
  • 36. Binary Trees Properties  Degenerate  Height = O(n) for n nodes  Similar to linked list  Balanced  Height = O( log(n) ) for n nodes  Useful for searches Degenerate binary tree Balanced binary tree
  • 37. Binary Search Properties  Time of search  Proportional to height of tree  Balanced binary tree  O( log(n) ) time  Degenerate tree  O( n ) time  Like searching linked list / unsorted array
  • 38. Binary Search Tree Construction  How to build & maintain binary trees?  Insertion  Deletion  Maintain key property (invariant)  Smaller values in left subtree  Larger values in right subtree
  • 39. Binary Search Tree – Insertion  Algorithm 1. Perform search for value X 2. Search will end at node Y (if X not in tree) 3. If X < Y, insert new leaf X as new left subtree for Y 4. If X > Y, insert new leaf X as new right subtree for Y  Observations  O( log(n) ) operation for balanced tree  Insertions may unbalance tree
  • 40. Example Insertion  Insert ( 20 ) 5 10 30 2 25 45 10 < 20, right 30 > 20, left 25 > 20, left Insert 20 on left 20
  • 41. Binary Search Tree – Deletion  Algorithm 1. Perform search for value X 2. If X is a leaf, delete X 3. Else // must delete internal node a) Replace with largest value Y on left subtree OR smallest value Z on right subtree b) Delete replacement value (Y or Z) from subtree Observation  O( log(n) ) operation for balanced tree  Deletions may unbalance tree
  • 42. Example Deletion (Leaf)  Delete ( 25 ) 5 10 30 2 25 45 10 < 25, right 30 > 25, left 25 = 25, delete 5 10 30 2 45
  • 43. Example Deletion (Internal Node)  Delete ( 10 ) 5 10 30 2 25 45 5 5 30 2 25 45 2 5 30 2 25 45 Replacing 10 with largest value in left subtree Replacing 5 with largest value in left subtree Deleting leaf
  • 44. Example Deletion (Internal Node)  Delete ( 10 ) 5 10 30 2 25 45 5 25 30 2 25 45 5 25 30 2 45 Replacing 10 with smallest value in right subtree Deleting leaf Resulting tree
  • 45. Balanced Search Trees  Kinds of balanced binary search trees  height balanced vs. weight balanced  “Tree rotations” used to maintain balance on insert/delete  Non-binary search trees  2/3 trees  each internal node has 2 or 3 children  all leaves at same depth (height balanced)  B-trees  Generalization of 2/3 trees  Each internal node has between k/2 and k children  Each node has an array of pointers to children  Widely used in databases
  • 46. Other (Non-Search) Trees  Parse trees  Convert from textual representation to tree representation  Textual program to tree  Used extensively in compilers  Tree representation of data  E.g. HTML data can be represented as a tree  called DOM (Document Object Model) tree  XML  Like HTML, but used to represent data  Tree structured
  • 47. Parse Trees  Expressions, programs, etc can be represented by tree structures  E.g. Arithmetic Expression Tree  A-(C/5 * 2) + (D*5 % 4) + - % A * * 4 / 2 D 5 C 5
  • 48. Tree Traversal  Goal: visit every node of a tree  in-order traversal void Node::inOrder () { if (left != NULL) { cout << “(“; left->inOrder(); cout << “)”; } cout << data << endl; if (right != NULL) right->inOrder() }Output: A – C / 5 * 2 + D * 5 % 4 To disambiguate: print brackets + - % A * * 4 / 2 D 5 C 5
  • 49. Tree Traversal (contd.)  pre-order and post-order: void Node::preOrder () { cout << data << endl; if (left != NULL) left->preOrder (); if (right != NULL) right->preOrder (); } void Node::postOrder () { if (left != NULL) left->preOrder (); if (right != NULL) right->preOrder (); cout << data << endl; } Output: + - A * / C 5 2 % * D 5 4 Output: A C 5 / 2 * - D 5 * 4 % + + - % A * * 4 / 2 D 5 C 5
  • 50. Graph Data Structures  E.g: Airline networks, road networks, electrical circuits  Nodes and Edges  E.g. representation: class Node  Stores name  stores pointers to all adjacent nodes  i,e. edge == pointer  To store multiple pointers: use array or linked list Ahm’bad Delhi Mumbai Calcutta Chennai Madurai