SlideShare une entreprise Scribd logo
1  sur  26
Télécharger pour lire hors ligne
First Year BA (IT)
CT1120 Algorithms
Lecture 17
Dr. Zia Ush Shamszaman
z.shamszaman1@nuigalway.ie
1
School of Computer Science, College of Science and Engineering
14-02-2020
Overview
•  Data Structure
–  Stack implementation
–  Queue implementation
–  Tree
–  Binary tree
•  Feedback and Assessment
214-02-2020
•  Given the following sequence of stack
operations, what is the top item on the stack
when the sequence is complete?
14-02-2020 3
m = Stack()
m.push('x')
m.push('y')
m.pop()
m.push('z')
m.peek()
•  Given the following sequence of stack
operations, what is the top item on the stack
when the sequence is complete?
14-02-2020 4
m = Stack()
m.push('x')
m.push('y')
m.pop()
m.push('z')
m.peek()
What this code is doing?
14-02-2020 5
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
print('nElements poped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('nStack after elements are poped:')
print(stack)
Stack implementation code
14-02-2020 6
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
print('nElements poped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('nStack after elements are poped:')
print(stack)
OUTPUT
Initial stack
['a', 'b', 'c']
Elements poped from stack:
c
b
a
Stack after elements are poped:
[]
What this code is doing?
14-02-2020 7
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("nQueue after removing elements")
print(queue)
What this code is doing?
14-02-2020 8
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("nQueue after removing elements")
print(queue)
Output
Initial queue
['a', 'b', 'c']
Elements dequeued from queue
a
b
c
Queue after removing elements
[]
Tree
•  A Tree is a collection of elements called nodes.
•  One of the node is distinguished as a root, along with a
relation (“parenthood”) that places a hierarchical
structure on the nodes.
14-02-2020 9
Applications of Tree
14-02-2020 10
Main applications of trees include:
1. Manipulate hierarchical data.
2. Make information easy to search (see tree
traversal).
3. Manipulate sorted lists of data.
4. As a workflow for compositing digital images for
visual effects.
5. Router algorithms
6. Form of a multi-stage decision-making (see
business chess).
Binary Tree
14-02-2020 11
•  A tree whose elements have at most 2 children is called a
binary tree.
•  Since each element in a binary tree can have only 2
children, we typically name the left child and right child.
Binary Tree
14-02-2020 12
•  A tree whose elements have at most 2 children is called a
binary tree.
•  Since each element in a binary tree can have only 2
children, we typically name the left child and right child.
((7+3)∗(5−2))
Binary Tree
14-02-2020 13
•  A tree whose elements have at most 2 children is called a
binary tree.
•  Since each element in a binary tree can have only 2
children, we typically name the left child and right child.
•  A Binary Tree node contains following parts.
•  Data
•  Pointer to left child
•  Pointer to right child
Python code of
Binary Tree
14-02-2020 14
# A class that represents an individual node in a
# Binary Tree
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
# create root
root = Node(1)
''' following is the tree after above statement
1
/ 
None None'''
root.left = Node(2);
root.right = Node(3);
''' 2 and 3 become left and right children of 1
1
/ 
2 3
/  / 
None None None None''’
root.left.left = Node(4);
'''4 becomes left child of 2
1
/ 
2 3
/  / 
4 None None None
/ 
None None'''
"__init__" is a reseved method in python classes. It is
called as a constructor in object oriented terminology. This
method is called when an object is created from a class
and it allows the class to initialize the attributes of the
class.
Tree traversal
14-02-2020 15
Following are the generally used ways for traversing trees:
•  Inorder: We recursively do an inorder traversal on the
left subtree, visit the root node, and finally do a recursive
inorder traversal of the right subtree.
•  Preorder: We visit the root node first, then recursively
do a preorder traversal of the left subtree, followed by a
recursive preorder traversal of the right subtree.
•  Postorder: We recursively do a postorder traversal of
the left subtree and the right subtree followed by a visit
to the root node.
Tree traversal
14-02-2020 16
(a) Inorder (Left, Root, Right) : 4 2 5 1 3
(b) Preorder (Root, Left, Right) : 1 2 4 5 3
(c) Postorder (Left, Right, Root) : 4 5 2 3 1
Level Order Traversal : 1 2 3 4 5
Tree traversal
14-02-2020 17
(a) Inorder (Left, Root, Right) : 4 2 5 1 3
(b) Preorder (Root, Left, Right) : 1 2 4 5 3
(c) Postorder (Left, Right, Root) : 4 5 2 3 1
Level Order Traversal : 1 2 3 4 5
Tree traversal code
14-02-2020 18
# A class that represents an individual node in a
Binary Tree
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
# A function to do inorder tree traversal
def printInorder(root):
if root:
# First recur on left child
printInorder(root.left)
# then print the data of node
print(root.val),
# now recur on right child
printInorder(root.right)
# A function to do postorder tree traversal
def printPostorder(root):
if root:
# First recur on left child
printPostorder(root.left)
# the recur on right child
printPostorder(root.right)
# now print the data of node
print(root.val),
# A function to do preorder tree traversal
def printPreorder(root):
if root:
# First print the data of node
print(root.val),
# Then recur on left child
printPreorder(root.left)
# Finally recur on right child
printPreorder(root.right)
# Driver code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print ("nPreorder traversal of binary tree is")
printPreorder(root)
print ("nInorder traversal of binary tree is")
printInorder(root)
print ("nPostorder traversal of binary tree is")
printPostorder(root)
Inorder traversal without recursion
14-02-2020 19
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Iterative function for inorder tree traversal
def inOrder(root):
# Set current to root of binary tree
current = root
stack = [] # initialize stack
done = 0
while True:
# Reach the left most Node of the current Node
if current is not None:
# Place pointer to a tree node on the stack
# before traversing the node's left subtree
stack.append(current)
current = current.left
# BackTrack from the empty subtree and visit the Nod
# at the top of the stack; however, if the stack is
# empty you are done
elif(stack):
current = stack.pop()
print(current.data, end=" ")
# Python 3 printing
# We have visited the node and its left
# subtree. Now, it's right subtree's turn
current = current.right
else:
break
print()
# Driver program to test above function
""" Constructed binary tree is
1
/ 
2 3
/ 
4 5 """
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
inOrder(root)
Priority Queue
14-02-2020 20
•  A priority queue acts like a queue in that you dequeue an item by
removing it from the front.
•  In a priority queue the logical order of items inside a queue is
determined by their priority.
•  The highest priority items are at the front of the queue and the lowest
priority items are at the back.
•  When you enqueue an item on a priority queue, the new item may move
all the way to the front.
Binary Heaps
14-02-2020 21
•  A Heap is a special Tree-based data structure in
which the tree is a complete binary tree. Generally,
Heaps can be of two types:
•  Max-Heap: The key present at the root node must be
greatest among the keys present at all of it’s children. The
same property must be recursively true for all sub-trees in
that Binary Tree.
•  Min-Heap: The key present at the root node must be
minimum among the keys present at all of it’s children. The
same property must be recursively true for all sub-trees in
that Binary Tree.
Binary Heap Operation
14-02-2020 22
The basic operations we will implement for our
binary heap are as follows:
•  BinaryHeap() creates a new, empty, binary heap.
•  insert(k) adds a new item to the heap.
•  findMin() returns the item with the minimum key value,
leaving item in the heap.
•  delMin() returns the item with the minimum key value,
removing the item from the heap.
•  isEmpty() returns true if the heap is empty, false
otherwise.
•  size() returns the number of items in the heap.
•  buildHeap(list) builds a new heap from a list of keys.
Next Lecture
14-02-2020 23
•  Binary Heap Implementation
•  Binary Search Tree
14-02-2020 24
Useful Links	
•  http://www.csanimated.com/animation.php?t=Quicksort
•  http://www.hakansozer.com/category/c/
•  http://www.nczonline.net/blog/2012/11/27/computer-science-in-
javascript-quicksort/
•  http://www.sorting-algorithms.com/shell-sort
•  https://www.tutorialspoint.com/
•  https://www.hackerearth.com/
•  www.khanacademy.org/computing/computer-science/algorithms
14-02-2020 25
Feedback & Assessment
14-02-2020 26

Contenu connexe

Tendances

Tendances (7)

Tree
TreeTree
Tree
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Tree
TreeTree
Tree
 
Introduction to pandas
Introduction to pandasIntroduction to pandas
Introduction to pandas
 
Pandas
PandasPandas
Pandas
 
Binary trees
Binary treesBinary trees
Binary trees
 
Introduction to data.table in R
Introduction to data.table in RIntroduction to data.table in R
Introduction to data.table in R
 

Similaire à L 17 ct1120

Similaire à L 17 ct1120 (20)

Binary tree
Binary treeBinary tree
Binary tree
 
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
TREE DATA STRUCTURE SLIDES dsa dsa .pptxTREE DATA STRUCTURE SLIDES dsa dsa .pptx
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
 
Binary Tree - Algorithms
Binary Tree - Algorithms Binary Tree - Algorithms
Binary Tree - Algorithms
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
 
L 19 ct1120
L 19 ct1120L 19 ct1120
L 19 ct1120
 
Unit iv data structure-converted
Unit  iv data structure-convertedUnit  iv data structure-converted
Unit iv data structure-converted
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Chapter 5_Trees.pdf
Chapter 5_Trees.pdfChapter 5_Trees.pdf
Chapter 5_Trees.pdf
 
Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02
 
Binary tree and operations
Binary tree and operations Binary tree and operations
Binary tree and operations
 
Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal Khan
 
Review session2
Review session2Review session2
Review session2
 
Binary Trees
Binary TreesBinary Trees
Binary Trees
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
Chap 5 Tree.ppt
Chap 5 Tree.pptChap 5 Tree.ppt
Chap 5 Tree.ppt
 
Trees
TreesTrees
Trees
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
 
Tree
TreeTree
Tree
 

Plus de Zia Ush Shamszaman

Pdfslide.net book of-abstracts-insight-student-conference-2015
Pdfslide.net book of-abstracts-insight-student-conference-2015Pdfslide.net book of-abstracts-insight-student-conference-2015
Pdfslide.net book of-abstracts-insight-student-conference-2015Zia Ush Shamszaman
 
Hacking with Backtrack Lecture-3
Hacking with Backtrack Lecture-3Hacking with Backtrack Lecture-3
Hacking with Backtrack Lecture-3Zia Ush Shamszaman
 
Hacking with Backtrack Lecture-2
Hacking with Backtrack Lecture-2Hacking with Backtrack Lecture-2
Hacking with Backtrack Lecture-2Zia Ush Shamszaman
 
Hacking with Backtrack Lecture-1
Hacking with Backtrack Lecture-1Hacking with Backtrack Lecture-1
Hacking with Backtrack Lecture-1Zia Ush Shamszaman
 
On the need for applications aware adaptive middleware in real-time RDF data ...
On the need for applications aware adaptive middleware in real-time RDF data ...On the need for applications aware adaptive middleware in real-time RDF data ...
On the need for applications aware adaptive middleware in real-time RDF data ...Zia Ush Shamszaman
 
On the need for applications aware adaptive middleware in real-time RDF data ...
On the need for applications aware adaptive middleware in real-time RDF data ...On the need for applications aware adaptive middleware in real-time RDF data ...
On the need for applications aware adaptive middleware in real-time RDF data ...Zia Ush Shamszaman
 
linear search and binary search
linear search and binary searchlinear search and binary search
linear search and binary searchZia Ush Shamszaman
 

Plus de Zia Ush Shamszaman (11)

Pdfslide.net book of-abstracts-insight-student-conference-2015
Pdfslide.net book of-abstracts-insight-student-conference-2015Pdfslide.net book of-abstracts-insight-student-conference-2015
Pdfslide.net book of-abstracts-insight-student-conference-2015
 
Hacking with Backtrack Lecture-3
Hacking with Backtrack Lecture-3Hacking with Backtrack Lecture-3
Hacking with Backtrack Lecture-3
 
Hacking with Backtrack Lecture-2
Hacking with Backtrack Lecture-2Hacking with Backtrack Lecture-2
Hacking with Backtrack Lecture-2
 
Hacking with Backtrack Lecture-1
Hacking with Backtrack Lecture-1Hacking with Backtrack Lecture-1
Hacking with Backtrack Lecture-1
 
On the need for applications aware adaptive middleware in real-time RDF data ...
On the need for applications aware adaptive middleware in real-time RDF data ...On the need for applications aware adaptive middleware in real-time RDF data ...
On the need for applications aware adaptive middleware in real-time RDF data ...
 
On the need for applications aware adaptive middleware in real-time RDF data ...
On the need for applications aware adaptive middleware in real-time RDF data ...On the need for applications aware adaptive middleware in real-time RDF data ...
On the need for applications aware adaptive middleware in real-time RDF data ...
 
L 18 ct1120
L 18 ct1120L 18 ct1120
L 18 ct1120
 
L 15 ct1120
L 15 ct1120L 15 ct1120
L 15 ct1120
 
L 14-ct1120
L 14-ct1120L 14-ct1120
L 14-ct1120
 
linear search and binary search
linear search and binary searchlinear search and binary search
linear search and binary search
 
Bangladesh
BangladeshBangladesh
Bangladesh
 

Dernier

Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightCheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightDelhi Call girls
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023ymrp368
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...amitlee9823
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...amitlee9823
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptxAnupama Kate
 
Week-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionWeek-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionfulawalesam
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxolyaivanovalion
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxolyaivanovalion
 
Discover Why Less is More in B2B Research
Discover Why Less is More in B2B ResearchDiscover Why Less is More in B2B Research
Discover Why Less is More in B2B Researchmichael115558
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% SecurePooja Nehwal
 
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...SUHANI PANDEY
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfRachmat Ramadhan H
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFxolyaivanovalion
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxolyaivanovalion
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...amitlee9823
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 

Dernier (20)

Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightCheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx
 
Week-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionWeek-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interaction
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptx
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFx
 
Discover Why Less is More in B2B Research
Discover Why Less is More in B2B ResearchDiscover Why Less is More in B2B Research
Discover Why Less is More in B2B Research
 
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
 
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFx
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 

L 17 ct1120

  • 1. First Year BA (IT) CT1120 Algorithms Lecture 17 Dr. Zia Ush Shamszaman z.shamszaman1@nuigalway.ie 1 School of Computer Science, College of Science and Engineering 14-02-2020
  • 2. Overview •  Data Structure –  Stack implementation –  Queue implementation –  Tree –  Binary tree •  Feedback and Assessment 214-02-2020
  • 3. •  Given the following sequence of stack operations, what is the top item on the stack when the sequence is complete? 14-02-2020 3 m = Stack() m.push('x') m.push('y') m.pop() m.push('z') m.peek()
  • 4. •  Given the following sequence of stack operations, what is the top item on the stack when the sequence is complete? 14-02-2020 4 m = Stack() m.push('x') m.push('y') m.pop() m.push('z') m.peek()
  • 5. What this code is doing? 14-02-2020 5 stack = [] stack.append('a') stack.append('b') stack.append('c') print('Initial stack') print(stack) print('nElements poped from stack:') print(stack.pop()) print(stack.pop()) print(stack.pop()) print('nStack after elements are poped:') print(stack)
  • 6. Stack implementation code 14-02-2020 6 stack = [] stack.append('a') stack.append('b') stack.append('c') print('Initial stack') print(stack) print('nElements poped from stack:') print(stack.pop()) print(stack.pop()) print(stack.pop()) print('nStack after elements are poped:') print(stack) OUTPUT Initial stack ['a', 'b', 'c'] Elements poped from stack: c b a Stack after elements are poped: []
  • 7. What this code is doing? 14-02-2020 7 queue = [] queue.append('a') queue.append('b') queue.append('c') print("Initial queue") print(queue) print("nElements dequeued from queue") print(queue.pop(0)) print(queue.pop(0)) print(queue.pop(0)) print("nQueue after removing elements") print(queue)
  • 8. What this code is doing? 14-02-2020 8 queue = [] queue.append('a') queue.append('b') queue.append('c') print("Initial queue") print(queue) print("nElements dequeued from queue") print(queue.pop(0)) print(queue.pop(0)) print(queue.pop(0)) print("nQueue after removing elements") print(queue) Output Initial queue ['a', 'b', 'c'] Elements dequeued from queue a b c Queue after removing elements []
  • 9. Tree •  A Tree is a collection of elements called nodes. •  One of the node is distinguished as a root, along with a relation (“parenthood”) that places a hierarchical structure on the nodes. 14-02-2020 9
  • 10. Applications of Tree 14-02-2020 10 Main applications of trees include: 1. Manipulate hierarchical data. 2. Make information easy to search (see tree traversal). 3. Manipulate sorted lists of data. 4. As a workflow for compositing digital images for visual effects. 5. Router algorithms 6. Form of a multi-stage decision-making (see business chess).
  • 11. Binary Tree 14-02-2020 11 •  A tree whose elements have at most 2 children is called a binary tree. •  Since each element in a binary tree can have only 2 children, we typically name the left child and right child.
  • 12. Binary Tree 14-02-2020 12 •  A tree whose elements have at most 2 children is called a binary tree. •  Since each element in a binary tree can have only 2 children, we typically name the left child and right child. ((7+3)∗(5−2))
  • 13. Binary Tree 14-02-2020 13 •  A tree whose elements have at most 2 children is called a binary tree. •  Since each element in a binary tree can have only 2 children, we typically name the left child and right child. •  A Binary Tree node contains following parts. •  Data •  Pointer to left child •  Pointer to right child
  • 14. Python code of Binary Tree 14-02-2020 14 # A class that represents an individual node in a # Binary Tree class Node: def __init__(self,key): self.left = None self.right = None self.val = key # create root root = Node(1) ''' following is the tree after above statement 1 / None None''' root.left = Node(2); root.right = Node(3); ''' 2 and 3 become left and right children of 1 1 / 2 3 / / None None None None''’ root.left.left = Node(4); '''4 becomes left child of 2 1 / 2 3 / / 4 None None None / None None''' "__init__" is a reseved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.
  • 15. Tree traversal 14-02-2020 15 Following are the generally used ways for traversing trees: •  Inorder: We recursively do an inorder traversal on the left subtree, visit the root node, and finally do a recursive inorder traversal of the right subtree. •  Preorder: We visit the root node first, then recursively do a preorder traversal of the left subtree, followed by a recursive preorder traversal of the right subtree. •  Postorder: We recursively do a postorder traversal of the left subtree and the right subtree followed by a visit to the root node.
  • 16. Tree traversal 14-02-2020 16 (a) Inorder (Left, Root, Right) : 4 2 5 1 3 (b) Preorder (Root, Left, Right) : 1 2 4 5 3 (c) Postorder (Left, Right, Root) : 4 5 2 3 1 Level Order Traversal : 1 2 3 4 5
  • 17. Tree traversal 14-02-2020 17 (a) Inorder (Left, Root, Right) : 4 2 5 1 3 (b) Preorder (Root, Left, Right) : 1 2 4 5 3 (c) Postorder (Left, Right, Root) : 4 5 2 3 1 Level Order Traversal : 1 2 3 4 5
  • 18. Tree traversal code 14-02-2020 18 # A class that represents an individual node in a Binary Tree class Node: def __init__(self,key): self.left = None self.right = None self.val = key # A function to do inorder tree traversal def printInorder(root): if root: # First recur on left child printInorder(root.left) # then print the data of node print(root.val), # now recur on right child printInorder(root.right) # A function to do postorder tree traversal def printPostorder(root): if root: # First recur on left child printPostorder(root.left) # the recur on right child printPostorder(root.right) # now print the data of node print(root.val), # A function to do preorder tree traversal def printPreorder(root): if root: # First print the data of node print(root.val), # Then recur on left child printPreorder(root.left) # Finally recur on right child printPreorder(root.right) # Driver code root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print ("nPreorder traversal of binary tree is") printPreorder(root) print ("nInorder traversal of binary tree is") printInorder(root) print ("nPostorder traversal of binary tree is") printPostorder(root)
  • 19. Inorder traversal without recursion 14-02-2020 19 # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Iterative function for inorder tree traversal def inOrder(root): # Set current to root of binary tree current = root stack = [] # initialize stack done = 0 while True: # Reach the left most Node of the current Node if current is not None: # Place pointer to a tree node on the stack # before traversing the node's left subtree stack.append(current) current = current.left # BackTrack from the empty subtree and visit the Nod # at the top of the stack; however, if the stack is # empty you are done elif(stack): current = stack.pop() print(current.data, end=" ") # Python 3 printing # We have visited the node and its left # subtree. Now, it's right subtree's turn current = current.right else: break print() # Driver program to test above function """ Constructed binary tree is 1 / 2 3 / 4 5 """ root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) inOrder(root)
  • 20. Priority Queue 14-02-2020 20 •  A priority queue acts like a queue in that you dequeue an item by removing it from the front. •  In a priority queue the logical order of items inside a queue is determined by their priority. •  The highest priority items are at the front of the queue and the lowest priority items are at the back. •  When you enqueue an item on a priority queue, the new item may move all the way to the front.
  • 21. Binary Heaps 14-02-2020 21 •  A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Generally, Heaps can be of two types: •  Max-Heap: The key present at the root node must be greatest among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree. •  Min-Heap: The key present at the root node must be minimum among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree.
  • 22. Binary Heap Operation 14-02-2020 22 The basic operations we will implement for our binary heap are as follows: •  BinaryHeap() creates a new, empty, binary heap. •  insert(k) adds a new item to the heap. •  findMin() returns the item with the minimum key value, leaving item in the heap. •  delMin() returns the item with the minimum key value, removing the item from the heap. •  isEmpty() returns true if the heap is empty, false otherwise. •  size() returns the number of items in the heap. •  buildHeap(list) builds a new heap from a list of keys.
  • 24. •  Binary Heap Implementation •  Binary Search Tree 14-02-2020 24
  • 25. Useful Links •  http://www.csanimated.com/animation.php?t=Quicksort •  http://www.hakansozer.com/category/c/ •  http://www.nczonline.net/blog/2012/11/27/computer-science-in- javascript-quicksort/ •  http://www.sorting-algorithms.com/shell-sort •  https://www.tutorialspoint.com/ •  https://www.hackerearth.com/ •  www.khanacademy.org/computing/computer-science/algorithms 14-02-2020 25