SlideShare a Scribd company logo
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 (17)

PDF
BinarySearchTree-bddicken
Benjamin Dicken
 
PPT
Phylogenetics in R
schamber
 
PPT
1.5 binary search tree
Krish_ver2
 
PPT
Binary Search Tree
Zafar Ayub
 
PPT
Manipulating strings
Nicole Ryan
 
PPTX
Phylogeny in R - Bianca Santini Sheffield R Users March 2015
Paul Richards
 
PPTX
Binary Tree in Data Structure
Meghaj Mallick
 
PPT
binary search tree
Shankar Bishnoi
 
PPTX
Trees in data structure
Anusruti Mitra
 
PDF
10 Red-Black Trees
Andres Mendez-Vazquez
 
PPT
Data Structure and Algorithms Binary Search Tree
ManishPrajapati78
 
PDF
Welcome to International Journal of Engineering Research and Development (IJERD)
IJERD Editor
 
PPT
Tree & bst
Shakil Ahmed
 
PDF
Mathematics: Addition Then Subtraction
LorenKnights
 
PPT
Trees
Saurabh Mishra
 
DOCX
Fast formula queries for functions, contexts, db is and packages
Feras Ahmad
 
PPTX
Binary Search Tree (BST)
M Sajid R
 
BinarySearchTree-bddicken
Benjamin Dicken
 
Phylogenetics in R
schamber
 
1.5 binary search tree
Krish_ver2
 
Binary Search Tree
Zafar Ayub
 
Manipulating strings
Nicole Ryan
 
Phylogeny in R - Bianca Santini Sheffield R Users March 2015
Paul Richards
 
Binary Tree in Data Structure
Meghaj Mallick
 
binary search tree
Shankar Bishnoi
 
Trees in data structure
Anusruti Mitra
 
10 Red-Black Trees
Andres Mendez-Vazquez
 
Data Structure and Algorithms Binary Search Tree
ManishPrajapati78
 
Welcome to International Journal of Engineering Research and Development (IJERD)
IJERD Editor
 
Tree & bst
Shakil Ahmed
 
Mathematics: Addition Then Subtraction
LorenKnights
 
Fast formula queries for functions, contexts, db is and packages
Feras Ahmad
 
Binary Search Tree (BST)
M Sajid R
 

Viewers also liked (8)

PDF
Applications of Factorial Function n=1 in determination of Specific Reaction ...
International Journal of Engineering Inventions www.ijeijournal.com
 
PPT
Lecture 2a arrays
Victor Palmar
 
PPTX
Data structures
Edward Blurock
 
PPT
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
PPT
DATA STRUCTURES
bca2010
 
Ad

Similar to Lecture9 recursion (20)

PPTX
Recursion and Sorting Algorithms
Afaq Mansoor Khan
 
PDF
Recursion.pdf
Flavia Tembo Kambale
 
PPT
Lec-6 Recursion of Data Structures & Algorithms
haseebanjum2611
 
PDF
Iterations and Recursions
Abdul Rahman Sherzad
 
PPT
14 recursion
Himadri Sen Gupta
 
PPTX
Recursion in Data Structure
khudabux1998
 
PPT
Recursion
Malainine Zaid
 
PPTX
10 - Recursive.pptx
bernadusseno
 
PPTX
Recursion(Advanced data structure)
kurubameena1
 
PPTX
(Recursion)ads
Ravi Rao
 
PDF
01 Notes Introduction Analysis of Algorithms Notes
Andres Mendez-Vazquez
 
PDF
Stanford splash spring 2016 basic programming
Yu-Sheng (Yosen) Chen
 
PDF
Chapter VII RECURSION.pdf algor and data structure
benyakoubrania53
 
PPTX
Recursion
Esther Leytush
 
PDF
PyOhio Recursion Slides
Rinita Gulliani
 
PPT
Recursion.ppt
ssuser53af97
 
PDF
Recursive algorithms in depth - Geek gap webinar #2
junior Teudjio
 
PPTX
lecture4-recursion.pptx
Lizhen Shi
 
PPT
FRbsbsvvsvsvbshgsgsvzvsvvsvsvsvsvsvvev.ppt
hassannadim591
 
PDF
Iteration, induction, and recursion
Mohammed Hussein
 
Recursion and Sorting Algorithms
Afaq Mansoor Khan
 
Recursion.pdf
Flavia Tembo Kambale
 
Lec-6 Recursion of Data Structures & Algorithms
haseebanjum2611
 
Iterations and Recursions
Abdul Rahman Sherzad
 
14 recursion
Himadri Sen Gupta
 
Recursion in Data Structure
khudabux1998
 
Recursion
Malainine Zaid
 
10 - Recursive.pptx
bernadusseno
 
Recursion(Advanced data structure)
kurubameena1
 
(Recursion)ads
Ravi Rao
 
01 Notes Introduction Analysis of Algorithms Notes
Andres Mendez-Vazquez
 
Stanford splash spring 2016 basic programming
Yu-Sheng (Yosen) Chen
 
Chapter VII RECURSION.pdf algor and data structure
benyakoubrania53
 
Recursion
Esther Leytush
 
PyOhio Recursion Slides
Rinita Gulliani
 
Recursion.ppt
ssuser53af97
 
Recursive algorithms in depth - Geek gap webinar #2
junior Teudjio
 
lecture4-recursion.pptx
Lizhen Shi
 
FRbsbsvvsvsvbshgsgsvzvsvvsvsvsvsvsvvev.ppt
hassannadim591
 
Iteration, induction, and recursion
Mohammed Hussein
 
Ad

More from Muhammad Zubair (13)

PPTX
Cloud computing
Muhammad Zubair
 
PPTX
Cloud computing disadvantages
Muhammad Zubair
 
PPT
Lecture8
Muhammad Zubair
 
PPT
Lecture7
Muhammad Zubair
 
PPT
Lecture6
Muhammad Zubair
 
PPT
Lecture5
Muhammad Zubair
 
PPT
Lecture4
Muhammad Zubair
 
PPT
Lecture3
Muhammad Zubair
 
PPT
Lecture3
Muhammad Zubair
 
PPT
Lecture2
Muhammad Zubair
 
PPT
Lecture1
Muhammad Zubair
 
DOCX
Indin report by zubair
Muhammad Zubair
 
DOCX
Cyber crime in pakistan by zubair
Muhammad Zubair
 
Cloud computing
Muhammad Zubair
 
Cloud computing disadvantages
Muhammad Zubair
 
Lecture8
Muhammad Zubair
 
Lecture7
Muhammad Zubair
 
Lecture6
Muhammad Zubair
 
Lecture5
Muhammad Zubair
 
Lecture4
Muhammad Zubair
 
Lecture3
Muhammad Zubair
 
Lecture3
Muhammad Zubair
 
Lecture2
Muhammad Zubair
 
Lecture1
Muhammad Zubair
 
Indin report by zubair
Muhammad Zubair
 
Cyber crime in pakistan by zubair
Muhammad Zubair
 

Recently uploaded (20)

PPTX
Latest Features in Odoo 18 - Odoo slides
Celine George
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
HEAD INJURY IN CHILDREN: NURSING MANAGEMENGT.pptx
PRADEEP ABOTHU
 
PPSX
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
PDF
The-Beginnings-of-Indian-Civilisation.pdf/6th class new ncert social/by k san...
Sandeep Swamy
 
PPTX
Nutri-QUIZ-Bee-Elementary.pptx...................
ferdinandsanbuenaven
 
PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PPTX
Gall bladder, Small intestine and Large intestine.pptx
rekhapositivity
 
PDF
1, 2, 3… E MAIS UM CICLO CHEGA AO FIM!.pdf
Colégio Santa Teresinha
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
Ramakrishna Reddy Bijjam
 
PPTX
LEGAL ASPECTS OF PSYCHIATRUC NURSING.pptx
PoojaSen20
 
PDF
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
PDF
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
PPTX
How to Configure Storno Accounting in Odoo 18 Accounting
Celine George
 
PPTX
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
PPTX
Capitol Doctoral Presentation -July 2025.pptx
CapitolTechU
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PDF
BÀI TẬP BỔ TRỢ THEO LESSON TIẾNG ANH - I-LEARN SMART WORLD 7 - CẢ NĂM - CÓ ĐÁ...
Nguyen Thanh Tu Collection
 
PPTX
PPT on the Development of Education in the Victorian England
Beena E S
 
Latest Features in Odoo 18 - Odoo slides
Celine George
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
HEAD INJURY IN CHILDREN: NURSING MANAGEMENGT.pptx
PRADEEP ABOTHU
 
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
The-Beginnings-of-Indian-Civilisation.pdf/6th class new ncert social/by k san...
Sandeep Swamy
 
Nutri-QUIZ-Bee-Elementary.pptx...................
ferdinandsanbuenaven
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
Gall bladder, Small intestine and Large intestine.pptx
rekhapositivity
 
1, 2, 3… E MAIS UM CICLO CHEGA AO FIM!.pdf
Colégio Santa Teresinha
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Pyhton with Mysql to perform CRUD operations.pptx
Ramakrishna Reddy Bijjam
 
LEGAL ASPECTS OF PSYCHIATRUC NURSING.pptx
PoojaSen20
 
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
How to Configure Storno Accounting in Odoo 18 Accounting
Celine George
 
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
Capitol Doctoral Presentation -July 2025.pptx
CapitolTechU
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
BÀI TẬP BỔ TRỢ THEO LESSON TIẾNG ANH - I-LEARN SMART WORLD 7 - CẢ NĂM - CÓ ĐÁ...
Nguyen Thanh Tu Collection
 
PPT on the Development of Education in the Victorian England
Beena E S
 

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.