SlideShare a Scribd company logo
1 of 30
Lecture # 9Lecture # 9
RecursionRecursion
 The programs we have discussed in previousThe programs we have discussed in previous
programming courses are generally structured asprogramming courses are generally structured as
functions that call one another in a disciplined,functions that call one another in a disciplined,
hierarchical manner.hierarchical manner.
 For some problems, it is useful to have functionsFor some problems, it is useful to have functions
call themselves.call themselves.
 AA recursive functionrecursive function is a function thatis a function that calls itselfcalls itself
either directly or indirectly through anothereither directly or indirectly through another
function.function.
 A recursive function is called to solve the problem.A recursive function is called to solve the problem.
The function actually knows how to solve theThe function actually knows how to solve the
simplest case (s) or so called Base Case (s).simplest case (s) or so called Base Case (s).
 If the function is called with a base case, theIf the function is called with a base case, the
function simply returns the result.function simply returns the result.
 If a function is called with more complex problem,If a function is called with more complex problem,
the function divides the problem into twothe function divides the problem into two
conceptual pieces:conceptual pieces:
 A piece the function knows how to do andA piece the function knows how to do and
 A piece the function doesn’t knows how to do.A piece the function doesn’t knows how to do.
 To make recursion feasible the latter piece (i.e.To make recursion feasible the latter piece (i.e.
piece the function doesn’t knows how to do )piece the function doesn’t knows how to do )
must resemble the original problem, but in themust resemble the original problem, but in the
form of slightly simpler or slightly smaller versionform of slightly simpler or slightly smaller version
of the original problem.of the original problem.
 Because this new problem looks like the originalBecause this new problem looks like the original
problem the functionproblem the function launcheslaunches (( callscalls ) a) a freshfresh
((newnew )) copycopy of itself to go to work on smallerof itself to go to work on smaller
problems. This is referred to as a recursive callproblems. This is referred to as a recursive call
and is also calledand is also called recursion steprecursion step..
Example : FactorialExample : Factorial
 Given a positive integer n,Given a positive integer n, nn factorial is defined asfactorial is defined as
the product of all integers betweenthe product of all integers between nn andand 11. for. for
example…example…
5! = 5 * 4 * 3 * 2 * 1 = 1205! = 5 * 4 * 3 * 2 * 1 = 120
0! = 10! = 1
soso
n! = 1n! = 1 if ( n== 0 )if ( n== 0 )
n! = n * ( n-1 ) * ( n-2 ) * ( n-3 ) …… * 1n! = n * ( n-1 ) * ( n-2 ) * ( n-3 ) …… * 1 if n> 0if n> 0
 So we can present an algorithm that acceptsSo we can present an algorithm that accepts
integerinteger nn and returns the value ofand returns the value of n!n! as follows.as follows.
int prod = 1, x, n;int prod = 1, x, n;
cin>>n;cin>>n;
for( x = n; x > 0; x-- )for( x = n; x > 0; x-- )
prod = prod * x;prod = prod * x;
cout<<n<<“ factorial is”<<prod;cout<<n<<“ factorial is”<<prod;
 Such an algorithm is calledSuch an algorithm is called iterativeiterative algorithmalgorithm
because it calls itself for the explicit (precise)because it calls itself for the explicit (precise)
repetition of some process until a certainrepetition of some process until a certain
condition is met.condition is met.
 In above programIn above program n!n! is calculated like as follows.is calculated like as follows.
0! = 10! = 1
1! = 11! = 1
2! = 2 * 12! = 2 * 1
3! = 3 * 2 * 13! = 3 * 2 * 1
4! = 4 * 3 * 2 * 14! = 4 * 3 * 2 * 1
 Let us see how the recursive definition of theLet us see how the recursive definition of the
factorial can be used to evaluatefactorial can be used to evaluate 5!5!..
1.1. 5! = 5 * 4!5! = 5 * 4!
2.2. 4! = 4 * 3!4! = 4 * 3!
3.3. 3! = 3 * 2!3! = 3 * 2!
4.4. 2! = 2 * 1!2! = 2 * 1!
5.5. 1! = 1 * 0!1! = 1 * 0!
6.6. 0! = 10! = 1
 In above each case is reduced to a simpler caseIn above each case is reduced to a simpler case
until we reach the caseuntil we reach the case 0!0! Which is definedWhich is defined
directly asdirectly as 11. we may therefore backtrack from. we may therefore backtrack from lineline
# 6# 6 toto line # 1line # 1 by returning the value computed inby returning the value computed in
one line to evaluate the result of previous line.one line to evaluate the result of previous line.
Lets incorporate this previousLets incorporate this previous
process of backward going into anprocess of backward going into an
algorithm as follows……..algorithm as follows……..
#include <iostream.h>#include <iostream.h>
#include <conio.h>#include <conio.h>
int factorial( int numb )int factorial( int numb )
{{
if( numb <= 0 )if( numb <= 0 )
return 1;return 1;
elseelse
return numb * factorial( numb - 1 );return numb * factorial( numb - 1 );
}//-------------------------------------------}//-------------------------------------------
void main()void main()
{{
clrscr();clrscr();
int n;int n;
cout<<" n Enter no for finding its Factorial.n";cout<<" n Enter no for finding its Factorial.n";
cin>>n;cin>>n;
cout<<"n Factorial of "<<n<<" is : "<<factorial( n );cout<<"n Factorial of "<<n<<" is : "<<factorial( n );
getch();getch();
}// end of main().}// end of main().
 Above code reflects recursive algorithm ofAbove code reflects recursive algorithm of n!.n!. InIn
this function is first called by main( ) and then itthis function is first called by main( ) and then it
callscalls itselfitself until it calculates the n! and finallyuntil it calculates the n! and finally
return it to main( ).return it to main( ).
Efficiency of RecursionEfficiency of Recursion
 In general, a non recursive version of a programIn general, a non recursive version of a program
will execute more efficiently in terms ofwill execute more efficiently in terms of timetime andand
spacespace than a recursive version. This is becausethan a recursive version. This is because
the overhead involved inthe overhead involved in enteringentering andand exitingexiting aa
new blocknew block ( system stack )( system stack ) is avoided in the nonis avoided in the non
recursive version.recursive version.
 However, sometimes a recursive solution is theHowever, sometimes a recursive solution is the
mostmost naturalnatural andand logicallogical way of solving a problemway of solving a problem
as we will soon observe while studying differentas we will soon observe while studying different
TreeTree data structuresdata structures..
TreesTrees
Tree Data StructuresTree Data Structures
Fazl-e-BasitFazl-e-Basit
Fazl-e-SubhanFazl-e-SubhanFazl-e-RahmanFazl-e-Rahman Saif-u-RahmanSaif-u-Rahman
Noor MuhammadNoor Muhammad
Fazl-e-QadirFazl-e-QadirNadirNadir QaiserQaiser SulemanSuleman FatimaFatima AA
 There are a number of applications where linearThere are a number of applications where linear
data structures are not appropriate. Consider adata structures are not appropriate. Consider a
genealogy (family tree) tree of a family.genealogy (family tree) tree of a family.
Tree Data StructureTree Data Structure
 AA linear linked listlinear linked list will not be able towill not be able to
capture the tree-like relationship withcapture the tree-like relationship with
ease.ease.
 Shortly, we will see that for applicationsShortly, we will see that for applications
that requirethat require searchingsearching, linear data, linear data
structures are not suitable.structures are not suitable.
 We will focus our attention onWe will focus our attention on binary treesbinary trees..
 Theorem:Theorem:
AA TreeTree withwith nn verticesvertices ( nodes )( nodes ) hashas n-n-
11 edgesedges..
Binary TreeBinary Tree
 AA Binary TreeBinary Tree is a finite set of elements that isis a finite set of elements that is
either empty or is partitioned intoeither empty or is partitioned into threethree disjointdisjoint
subsets. Thesubsets. The firstfirst subset contains a singlesubset contains a single
element called aelement called a rootroot of the tree. Theof the tree. The other twoother two
subsets are themselves binary trees, called thesubsets are themselves binary trees, called the
leftleft andand rightright sub trees of the original tree.sub trees of the original tree.
 AA leftleft oror rightright sub tree can besub tree can be emptyempty..
 Each element of aEach element of a binary treebinary tree is called ais called a nodenode ofof
the tree.the tree.
 Following is an example ofFollowing is an example of binary treebinary tree. This tree. This tree
consists ofconsists of ninenine nodes withnodes with AA as its root. Itsas its root. Its leftleft
sub tree is rooted atsub tree is rooted at BB and itsand its rightright sub tree issub tree is
rooted atrooted at CC..
AA
BB
GG
EE
IIHH
FF
CC
DD
Figure 1Figure 1
Binary TreeBinary Tree
 TheThe absenceabsence of a branch indicates anyof a branch indicates any emptyempty
sub treesub tree. For example in previous figure, the. For example in previous figure, the leftleft
sub tree of thesub tree of the binary treebinary tree rooted atrooted at CC isis emptyempty..
 Figures below shows that areFigures below shows that are notnot Binary TreesBinary Trees..
AA
BB
GG
EE
II
FF
HH
CC
DD
AA
BB
GG
EE
II
FF
HH
CC
DD
Figure 2Figure 2 Figure 3Figure 3
 IfIf AA is the root of binary tree andis the root of binary tree and BB is the root ofis the root of
itsits leftleft oror rightright sub tree, thensub tree, then AA is said to beis said to be fatherfather
oror parentparent ofof BB andand BB is said to beis said to be leftleft oror rightright sonson
(( childchild ) of) of AA..
 A node that has no child ( son ) is calledA node that has no child ( son ) is called leafleaf..
 NodeNode n1n1 is anis an ancestorancestor of nodeof node n2n2 ( and( and n2n2 is ais a
descendentdescendent ofof n1n1 ) if) if n1n1 is either theis either the parentparent ofof n2n2
or the parent ofor the parent of somesome ancestorancestor ofof n2n2. For. For
example in previousexample in previous Figure 1Figure 1 AA is anis an ancestorancestor ofof
GG andand HH is ais a descendentdescendent ofof CC, but, but EE is neither ais neither a
descendentdescendent nornor ancestorancestor ofof CC..
 IfIf every non leaf nodeevery non leaf node in a binary tree has nonin a binary tree has non
empty left and right sub trees, the tree is termedempty left and right sub trees, the tree is termed
asas strictly binary treestrictly binary tree. Following. Following Figure 4Figure 4 is strictlyis strictly
binary tree whilebinary tree while Figure 1Figure 1 is not.is not.
 AA strictly binary treestrictly binary tree withwith nn leaves always containleaves always contain
2n – 12n – 1 nodes.nodes.
AA
BB
DD
GG
EE
FF
CC
Figure 4Figure 4
 TheThe levellevel of a node in a binary tree is defined asof a node in a binary tree is defined as
followsfollows :->:-> TheThe rootroot of the tree hasof the tree has level 0level 0, and the, and the
level of any other node in the tree islevel of any other node in the tree is one moreone more thanthan
the level of itsthe level of its parentparent. For example in. For example in Figure 1Figure 1
nodenode EE is atis at level 2level 2 and nodeand node HH is atis at level 3level 3..
 TheThe depthdepth of a binary tree is theof a binary tree is the maximum levelmaximum level ofof
anyany leafleaf in the tree. Thus depth ofin the tree. Thus depth of Figure 1Figure 1 isis 33..
 AA Complete Binary TreeComplete Binary Tree ,is a binary tree in which,is a binary tree in which
each level of the tree is completely filled excepteach level of the tree is completely filled except
possibly the bottom level, and in this level thepossibly the bottom level, and in this level the
nodes are in the left most positionsnodes are in the left most positions. For example,. For example,
Complete Binary TreeComplete Binary Tree
 AA complete binary treecomplete binary tree of depthof depth dd is theis the strictlystrictly
Complete binaryComplete binary if all of whose leaves are at levelif all of whose leaves are at level dd..
Complete Binary TreeComplete Binary Tree
 AA complete binary treecomplete binary tree of depthof depth dd is theis the strictlystrictly
binarybinary all of whose leaves are at levelall of whose leaves are at level dd..
AA
BB
DD GGEE FF
CC
Strictly Complete Binary TreeStrictly Complete Binary Tree
AA
BB
DD GGEE FF
CC
Complete Binary TreeComplete Binary Tree
HH
AA
BB
DD FFEE
CC
Not Complete Binary TreeNot Complete Binary Tree
 Another common property is toAnother common property is to traversetraverse a binarya binary
tree i.e. to pass through the tree, i.e.tree i.e. to pass through the tree, i.e.
enumerating or visiting each of its nodes once.enumerating or visiting each of its nodes once.
Thank You……Thank You……

More Related Content

What's hot

BinarySearchTree-bddicken
BinarySearchTree-bddickenBinarySearchTree-bddicken
BinarySearchTree-bddickenBenjamin Dicken
 
Phylogenetics in R
Phylogenetics in RPhylogenetics in R
Phylogenetics in Rschamber
 
1.5 binary search tree
1.5 binary search tree1.5 binary search tree
1.5 binary search treeKrish_ver2
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search TreeZafar Ayub
 
Manipulating strings
Manipulating stringsManipulating strings
Manipulating stringsNicole Ryan
 
Phylogeny in R - Bianca Santini Sheffield R Users March 2015
Phylogeny in R - Bianca Santini Sheffield R Users March 2015Phylogeny in R - Bianca Santini Sheffield R Users March 2015
Phylogeny in R - Bianca Santini Sheffield R Users March 2015Paul Richards
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data StructureMeghaj Mallick
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structureAnusruti Mitra
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeManishPrajapati78
 
Welcome to International Journal of Engineering Research and Development (IJERD)
Welcome to International Journal of Engineering Research and Development (IJERD)Welcome to International Journal of Engineering Research and Development (IJERD)
Welcome to International Journal of Engineering Research and Development (IJERD)IJERD Editor
 
Mathematics: Addition Then Subtraction
Mathematics: Addition Then  Subtraction Mathematics: Addition Then  Subtraction
Mathematics: Addition Then Subtraction LorenKnights
 
Fast formula queries for functions, contexts, db is and packages
Fast formula queries for functions, contexts, db is and packagesFast formula queries for functions, contexts, db is and packages
Fast formula queries for functions, contexts, db is and packagesFeras Ahmad
 
Binary Search Tree (BST)
Binary Search Tree (BST)Binary Search Tree (BST)
Binary Search Tree (BST)M Sajid R
 

What's hot (17)

BinarySearchTree-bddicken
BinarySearchTree-bddickenBinarySearchTree-bddicken
BinarySearchTree-bddicken
 
Phylogenetics in R
Phylogenetics in RPhylogenetics in R
Phylogenetics in R
 
1.5 binary search tree
1.5 binary search tree1.5 binary search tree
1.5 binary search tree
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Manipulating strings
Manipulating stringsManipulating strings
Manipulating strings
 
Phylogeny in R - Bianca Santini Sheffield R Users March 2015
Phylogeny in R - Bianca Santini Sheffield R Users March 2015Phylogeny in R - Bianca Santini Sheffield R Users March 2015
Phylogeny in R - Bianca Santini Sheffield R Users March 2015
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
 
binary search tree
binary search treebinary search tree
binary search tree
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
 
10 Red-Black Trees
10 Red-Black Trees10 Red-Black Trees
10 Red-Black Trees
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
 
Welcome to International Journal of Engineering Research and Development (IJERD)
Welcome to International Journal of Engineering Research and Development (IJERD)Welcome to International Journal of Engineering Research and Development (IJERD)
Welcome to International Journal of Engineering Research and Development (IJERD)
 
Tree & bst
Tree & bstTree & bst
Tree & bst
 
Mathematics: Addition Then Subtraction
Mathematics: Addition Then  Subtraction Mathematics: Addition Then  Subtraction
Mathematics: Addition Then Subtraction
 
Trees
TreesTrees
Trees
 
Fast formula queries for functions, contexts, db is and packages
Fast formula queries for functions, contexts, db is and packagesFast formula queries for functions, contexts, db is and packages
Fast formula queries for functions, contexts, db is and packages
 
Binary Search Tree (BST)
Binary Search Tree (BST)Binary Search Tree (BST)
Binary Search Tree (BST)
 

Viewers also liked (8)

Applications of Factorial Function n=1 in determination of Specific Reaction ...
Applications of Factorial Function n=1 in determination of Specific Reaction ...Applications of Factorial Function n=1 in determination of Specific Reaction ...
Applications of Factorial Function n=1 in determination of Specific Reaction ...
 
Lecture 2a arrays
Lecture 2a arraysLecture 2a arrays
Lecture 2a arrays
 
Data structures
Data structuresData structures
Data structures
 
F04123137
F04123137F04123137
F04123137
 
G04123844
G04123844G04123844
G04123844
 
H04124548
H04124548H04124548
H04124548
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURES
 

Similar to Lecture9 recursion

Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structurecogaxor346
 
Python recursion
Python recursionPython recursion
Python recursionToniyaP1
 
app4.pptx
app4.pptxapp4.pptx
app4.pptxsg4795
 
lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptxLizhen Shi
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programmingJay Nagar
 
Recursion(Advanced data structure)
Recursion(Advanced data structure)Recursion(Advanced data structure)
Recursion(Advanced data structure)kurubameena1
 
Notes5
Notes5Notes5
Notes5hccit
 
(Recursion)ads
(Recursion)ads(Recursion)ads
(Recursion)adsRavi Rao
 
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...Simplilearn
 
Unit 05 - Limits and Continuity.pdf
Unit 05 - Limits and Continuity.pdfUnit 05 - Limits and Continuity.pdf
Unit 05 - Limits and Continuity.pdfSagarPetwal
 
Chapter 7 recursion handouts with notes
Chapter 7   recursion handouts with notesChapter 7   recursion handouts with notes
Chapter 7 recursion handouts with notesmailund
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdfjamvantsolanki
 
2022-9-recursive-1.pptx
2022-9-recursive-1.pptx2022-9-recursive-1.pptx
2022-9-recursive-1.pptxRayLee547290
 
Lecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptxLecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptxAbuHuraira729502
 
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx15AnasKhan
 

Similar to Lecture9 recursion (20)

Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structure
 
Python recursion
Python recursionPython recursion
Python recursion
 
app4.pptx
app4.pptxapp4.pptx
app4.pptx
 
lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptx
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Recursion(Advanced data structure)
Recursion(Advanced data structure)Recursion(Advanced data structure)
Recursion(Advanced data structure)
 
Notes5
Notes5Notes5
Notes5
 
(Recursion)ads
(Recursion)ads(Recursion)ads
(Recursion)ads
 
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
 
Unit 05 - Limits and Continuity.pdf
Unit 05 - Limits and Continuity.pdfUnit 05 - Limits and Continuity.pdf
Unit 05 - Limits and Continuity.pdf
 
Chapter 7 recursion handouts with notes
Chapter 7   recursion handouts with notesChapter 7   recursion handouts with notes
Chapter 7 recursion handouts with notes
 
FUNDAMETAL ALG.ppt
FUNDAMETAL ALG.pptFUNDAMETAL ALG.ppt
FUNDAMETAL ALG.ppt
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
 
2022-9-recursive-1.pptx
2022-9-recursive-1.pptx2022-9-recursive-1.pptx
2022-9-recursive-1.pptx
 
Recursion part 2
Recursion part 2Recursion part 2
Recursion part 2
 
Lecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptxLecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptx
 
Cis068 08
Cis068 08Cis068 08
Cis068 08
 
Recursion CBSE Class 12
Recursion CBSE Class 12Recursion CBSE Class 12
Recursion CBSE Class 12
 
Recursion.pdf
Recursion.pdfRecursion.pdf
Recursion.pdf
 
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
 

More from Muhammad Zubair (13)

Cloud computing
Cloud computingCloud computing
Cloud computing
 
Cloud computing disadvantages
Cloud computing disadvantagesCloud computing disadvantages
Cloud computing disadvantages
 
Lecture8
Lecture8Lecture8
Lecture8
 
Lecture7
Lecture7Lecture7
Lecture7
 
Lecture6
Lecture6Lecture6
Lecture6
 
Lecture5
Lecture5Lecture5
Lecture5
 
Lecture4
Lecture4Lecture4
Lecture4
 
Lecture3
Lecture3Lecture3
Lecture3
 
Lecture3
Lecture3Lecture3
Lecture3
 
Lecture2
Lecture2Lecture2
Lecture2
 
Lecture1
Lecture1Lecture1
Lecture1
 
Indin report by zubair
Indin report by zubairIndin report by zubair
Indin report by zubair
 
Cyber crime in pakistan by zubair
Cyber crime in pakistan by zubairCyber crime in pakistan by zubair
Cyber crime in pakistan by zubair
 

Recently uploaded

INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsPooky Knightsmith
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 

Recently uploaded (20)

INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young minds
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 

Lecture9 recursion

  • 3.  The programs we have discussed in previousThe programs we have discussed in previous programming courses are generally structured asprogramming courses are generally structured as functions that call one another in a disciplined,functions that call one another in a disciplined, hierarchical manner.hierarchical manner.  For some problems, it is useful to have functionsFor some problems, it is useful to have functions call themselves.call themselves.  AA recursive functionrecursive function is a function thatis a function that calls itselfcalls itself either directly or indirectly through anothereither directly or indirectly through another function.function.
  • 4.  A recursive function is called to solve the problem.A recursive function is called to solve the problem. The function actually knows how to solve theThe function actually knows how to solve the simplest case (s) or so called Base Case (s).simplest case (s) or so called Base Case (s).  If the function is called with a base case, theIf the function is called with a base case, the function simply returns the result.function simply returns the result.  If a function is called with more complex problem,If a function is called with more complex problem, the function divides the problem into twothe function divides the problem into two conceptual pieces:conceptual pieces:  A piece the function knows how to do andA piece the function knows how to do and  A piece the function doesn’t knows how to do.A piece the function doesn’t knows how to do.
  • 5.  To make recursion feasible the latter piece (i.e.To make recursion feasible the latter piece (i.e. piece the function doesn’t knows how to do )piece the function doesn’t knows how to do ) must resemble the original problem, but in themust resemble the original problem, but in the form of slightly simpler or slightly smaller versionform of slightly simpler or slightly smaller version of the original problem.of the original problem.  Because this new problem looks like the originalBecause this new problem looks like the original problem the functionproblem the function launcheslaunches (( callscalls ) a) a freshfresh ((newnew )) copycopy of itself to go to work on smallerof itself to go to work on smaller problems. This is referred to as a recursive callproblems. This is referred to as a recursive call and is also calledand is also called recursion steprecursion step..
  • 6. Example : FactorialExample : Factorial  Given a positive integer n,Given a positive integer n, nn factorial is defined asfactorial is defined as the product of all integers betweenthe product of all integers between nn andand 11. for. for example…example… 5! = 5 * 4 * 3 * 2 * 1 = 1205! = 5 * 4 * 3 * 2 * 1 = 120 0! = 10! = 1 soso n! = 1n! = 1 if ( n== 0 )if ( n== 0 ) n! = n * ( n-1 ) * ( n-2 ) * ( n-3 ) …… * 1n! = n * ( n-1 ) * ( n-2 ) * ( n-3 ) …… * 1 if n> 0if n> 0
  • 7.  So we can present an algorithm that acceptsSo we can present an algorithm that accepts integerinteger nn and returns the value ofand returns the value of n!n! as follows.as follows. int prod = 1, x, n;int prod = 1, x, n; cin>>n;cin>>n; for( x = n; x > 0; x-- )for( x = n; x > 0; x-- ) prod = prod * x;prod = prod * x; cout<<n<<“ factorial is”<<prod;cout<<n<<“ factorial is”<<prod;  Such an algorithm is calledSuch an algorithm is called iterativeiterative algorithmalgorithm because it calls itself for the explicit (precise)because it calls itself for the explicit (precise) repetition of some process until a certainrepetition of some process until a certain condition is met.condition is met.
  • 8.  In above programIn above program n!n! is calculated like as follows.is calculated like as follows. 0! = 10! = 1 1! = 11! = 1 2! = 2 * 12! = 2 * 1 3! = 3 * 2 * 13! = 3 * 2 * 1 4! = 4 * 3 * 2 * 14! = 4 * 3 * 2 * 1
  • 9.  Let us see how the recursive definition of theLet us see how the recursive definition of the factorial can be used to evaluatefactorial can be used to evaluate 5!5!.. 1.1. 5! = 5 * 4!5! = 5 * 4! 2.2. 4! = 4 * 3!4! = 4 * 3! 3.3. 3! = 3 * 2!3! = 3 * 2! 4.4. 2! = 2 * 1!2! = 2 * 1! 5.5. 1! = 1 * 0!1! = 1 * 0! 6.6. 0! = 10! = 1  In above each case is reduced to a simpler caseIn above each case is reduced to a simpler case until we reach the caseuntil we reach the case 0!0! Which is definedWhich is defined directly asdirectly as 11. we may therefore backtrack from. we may therefore backtrack from lineline # 6# 6 toto line # 1line # 1 by returning the value computed inby returning the value computed in one line to evaluate the result of previous line.one line to evaluate the result of previous line.
  • 10. Lets incorporate this previousLets incorporate this previous process of backward going into anprocess of backward going into an algorithm as follows……..algorithm as follows……..
  • 11. #include <iostream.h>#include <iostream.h> #include <conio.h>#include <conio.h> int factorial( int numb )int factorial( int numb ) {{ if( numb <= 0 )if( numb <= 0 ) return 1;return 1; elseelse return numb * factorial( numb - 1 );return numb * factorial( numb - 1 ); }//-------------------------------------------}//------------------------------------------- void main()void main() {{ clrscr();clrscr(); int n;int n; cout<<" n Enter no for finding its Factorial.n";cout<<" n Enter no for finding its Factorial.n"; cin>>n;cin>>n; cout<<"n Factorial of "<<n<<" is : "<<factorial( n );cout<<"n Factorial of "<<n<<" is : "<<factorial( n ); getch();getch(); }// end of main().}// end of main().
  • 12.  Above code reflects recursive algorithm ofAbove code reflects recursive algorithm of n!.n!. InIn this function is first called by main( ) and then itthis function is first called by main( ) and then it callscalls itselfitself until it calculates the n! and finallyuntil it calculates the n! and finally return it to main( ).return it to main( ).
  • 13. Efficiency of RecursionEfficiency of Recursion  In general, a non recursive version of a programIn general, a non recursive version of a program will execute more efficiently in terms ofwill execute more efficiently in terms of timetime andand spacespace than a recursive version. This is becausethan a recursive version. This is because the overhead involved inthe overhead involved in enteringentering andand exitingexiting aa new blocknew block ( system stack )( system stack ) is avoided in the nonis avoided in the non recursive version.recursive version.  However, sometimes a recursive solution is theHowever, sometimes a recursive solution is the mostmost naturalnatural andand logicallogical way of solving a problemway of solving a problem as we will soon observe while studying differentas we will soon observe while studying different TreeTree data structuresdata structures..
  • 15. Tree Data StructuresTree Data Structures Fazl-e-BasitFazl-e-Basit Fazl-e-SubhanFazl-e-SubhanFazl-e-RahmanFazl-e-Rahman Saif-u-RahmanSaif-u-Rahman Noor MuhammadNoor Muhammad Fazl-e-QadirFazl-e-QadirNadirNadir QaiserQaiser SulemanSuleman FatimaFatima AA  There are a number of applications where linearThere are a number of applications where linear data structures are not appropriate. Consider adata structures are not appropriate. Consider a genealogy (family tree) tree of a family.genealogy (family tree) tree of a family.
  • 16. Tree Data StructureTree Data Structure  AA linear linked listlinear linked list will not be able towill not be able to capture the tree-like relationship withcapture the tree-like relationship with ease.ease.  Shortly, we will see that for applicationsShortly, we will see that for applications that requirethat require searchingsearching, linear data, linear data structures are not suitable.structures are not suitable.  We will focus our attention onWe will focus our attention on binary treesbinary trees..
  • 17.  Theorem:Theorem: AA TreeTree withwith nn verticesvertices ( nodes )( nodes ) hashas n-n- 11 edgesedges..
  • 19.  AA Binary TreeBinary Tree is a finite set of elements that isis a finite set of elements that is either empty or is partitioned intoeither empty or is partitioned into threethree disjointdisjoint subsets. Thesubsets. The firstfirst subset contains a singlesubset contains a single element called aelement called a rootroot of the tree. Theof the tree. The other twoother two subsets are themselves binary trees, called thesubsets are themselves binary trees, called the leftleft andand rightright sub trees of the original tree.sub trees of the original tree.  AA leftleft oror rightright sub tree can besub tree can be emptyempty..  Each element of aEach element of a binary treebinary tree is called ais called a nodenode ofof the tree.the tree.
  • 20.  Following is an example ofFollowing is an example of binary treebinary tree. This tree. This tree consists ofconsists of ninenine nodes withnodes with AA as its root. Itsas its root. Its leftleft sub tree is rooted atsub tree is rooted at BB and itsand its rightright sub tree issub tree is rooted atrooted at CC.. AA BB GG EE IIHH FF CC DD Figure 1Figure 1
  • 22.  TheThe absenceabsence of a branch indicates anyof a branch indicates any emptyempty sub treesub tree. For example in previous figure, the. For example in previous figure, the leftleft sub tree of thesub tree of the binary treebinary tree rooted atrooted at CC isis emptyempty..  Figures below shows that areFigures below shows that are notnot Binary TreesBinary Trees.. AA BB GG EE II FF HH CC DD AA BB GG EE II FF HH CC DD Figure 2Figure 2 Figure 3Figure 3
  • 23.  IfIf AA is the root of binary tree andis the root of binary tree and BB is the root ofis the root of itsits leftleft oror rightright sub tree, thensub tree, then AA is said to beis said to be fatherfather oror parentparent ofof BB andand BB is said to beis said to be leftleft oror rightright sonson (( childchild ) of) of AA..  A node that has no child ( son ) is calledA node that has no child ( son ) is called leafleaf..  NodeNode n1n1 is anis an ancestorancestor of nodeof node n2n2 ( and( and n2n2 is ais a descendentdescendent ofof n1n1 ) if) if n1n1 is either theis either the parentparent ofof n2n2 or the parent ofor the parent of somesome ancestorancestor ofof n2n2. For. For example in previousexample in previous Figure 1Figure 1 AA is anis an ancestorancestor ofof GG andand HH is ais a descendentdescendent ofof CC, but, but EE is neither ais neither a descendentdescendent nornor ancestorancestor ofof CC..
  • 24.  IfIf every non leaf nodeevery non leaf node in a binary tree has nonin a binary tree has non empty left and right sub trees, the tree is termedempty left and right sub trees, the tree is termed asas strictly binary treestrictly binary tree. Following. Following Figure 4Figure 4 is strictlyis strictly binary tree whilebinary tree while Figure 1Figure 1 is not.is not.  AA strictly binary treestrictly binary tree withwith nn leaves always containleaves always contain 2n – 12n – 1 nodes.nodes. AA BB DD GG EE FF CC Figure 4Figure 4
  • 25.  TheThe levellevel of a node in a binary tree is defined asof a node in a binary tree is defined as followsfollows :->:-> TheThe rootroot of the tree hasof the tree has level 0level 0, and the, and the level of any other node in the tree islevel of any other node in the tree is one moreone more thanthan the level of itsthe level of its parentparent. For example in. For example in Figure 1Figure 1 nodenode EE is atis at level 2level 2 and nodeand node HH is atis at level 3level 3..  TheThe depthdepth of a binary tree is theof a binary tree is the maximum levelmaximum level ofof anyany leafleaf in the tree. Thus depth ofin the tree. Thus depth of Figure 1Figure 1 isis 33..  AA Complete Binary TreeComplete Binary Tree ,is a binary tree in which,is a binary tree in which each level of the tree is completely filled excepteach level of the tree is completely filled except possibly the bottom level, and in this level thepossibly the bottom level, and in this level the nodes are in the left most positionsnodes are in the left most positions. For example,. For example,
  • 26. Complete Binary TreeComplete Binary Tree  AA complete binary treecomplete binary tree of depthof depth dd is theis the strictlystrictly Complete binaryComplete binary if all of whose leaves are at levelif all of whose leaves are at level dd..
  • 27. Complete Binary TreeComplete Binary Tree  AA complete binary treecomplete binary tree of depthof depth dd is theis the strictlystrictly binarybinary all of whose leaves are at levelall of whose leaves are at level dd..
  • 28. AA BB DD GGEE FF CC Strictly Complete Binary TreeStrictly Complete Binary Tree AA BB DD GGEE FF CC Complete Binary TreeComplete Binary Tree HH AA BB DD FFEE CC Not Complete Binary TreeNot Complete Binary Tree
  • 29.  Another common property is toAnother common property is to traversetraverse a binarya binary tree i.e. to pass through the tree, i.e.tree i.e. to pass through the tree, i.e. enumerating or visiting each of its nodes once.enumerating or visiting each of its nodes once.