lecture9 recursion

30
Lecture # 9 Lecture # 9

Upload: muhammad-zubair

Post on 13-Apr-2017

159 views

Category:

Education


0 download

TRANSCRIPT

Page 1: Lecture9 recursion

Lecture # 9Lecture # 9

Page 2: Lecture9 recursion

RecursionRecursion

Page 3: Lecture9 recursion

The programs we have discussed in The programs we have discussed in previous programming courses are previous programming courses are generally structured as functions that call generally structured as functions that call one another in a disciplined, hierarchical one another in a disciplined, hierarchical manner.manner.

For some problems, it is useful to have For some problems, it is useful to have functions call themselves.functions call themselves.

A A recursive functionrecursive function is a function that is a function that calls calls itselfitself either directly or indirectly through either directly or indirectly through another function.another function.

Page 4: Lecture9 recursion

A recursive function is called to solve the A recursive function is called to solve the problem. The function actually knows how to problem. The function actually knows how to solve the simplest case (s) or so called Base solve the simplest case (s) or so called Base Case (s).Case (s).

If the function is called with a base case, the If 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 If a function is called with more complex problem, the function divides the problem problem, the function divides the problem into two conceptual pieces:into two 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.

Page 5: Lecture9 recursion

To make recursion feasible the latter piece To make recursion feasible the latter piece (i.e. piece the function doesn’t knows how (i.e. piece the function doesn’t knows how to do ) must resemble the original to do ) must resemble the original problem, but in the form of slightly simpler problem, but in the form of slightly simpler or slightly smaller version of the original or slightly smaller version of the original problem.problem.

Because this new problem looks like the Because this new problem looks like the original problem the function original problem the function launcheslaunches ( ( calls calls ) a ) a freshfresh ( (newnew ) ) copycopy of itself to go to of itself to go to work on smaller problems. This is referred work on smaller problems. This is referred to as a recursive call and is also called to as a recursive call and is also called recursion steprecursion step..

Page 6: Lecture9 recursion

Example : FactorialExample : Factorial Given a positive integer n, Given a positive integer n, nn factorial is factorial is

defined as the product of all integers between defined as the product of all integers between nn and and 11. for example…. for example…

5! = 5 * 4 * 3 * 2 * 1 = 1205! = 5 * 4 * 3 * 2 * 1 = 120 0! = 10! = 1

so so n! = 1 n! = 1 if ( n== 0 )if ( n== 0 ) n! = n * ( n-1 ) * ( n-2 ) * ( n-3 ) …… * 1 n! = n * ( n-1 ) * ( n-2 ) * ( n-3 ) …… * 1 if n> 0if n> 0

Page 7: Lecture9 recursion

So we can present an algorithm that accepts So we can present an algorithm that accepts integer integer nn and returns the value of and returns the value of n!n! as as follows.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 called Such an algorithm is called iterativeiterative algorithm because it calls itself for the algorithm because it calls itself for the explicit (precise) repetition of some process explicit (precise) repetition of some process until a certain condition is met.until a certain condition is met.

Page 8: Lecture9 recursion

In above program In above program n!n! is calculated like as is calculated like as follows.follows.

0! = 10! = 11! = 11! = 12! = 2 * 12! = 2 * 13! = 3 * 2 * 13! = 3 * 2 * 14! = 4 * 3 * 2 * 14! = 4 * 3 * 2 * 1

Page 9: Lecture9 recursion

Let us see how the recursive definition of Let us see how the recursive definition of the factorial can be used to evaluate the factorial 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 In above each case is reduced to a simpler case until we reach the case case until we reach the case 0!0! Which is Which is defined directly as defined directly as 11. we may therefore . we may therefore backtrack from backtrack from line # 6line # 6 to to line # 1line # 1 by by returning the value computed in one line to returning the value computed in one line to evaluate the result of previous line.evaluate the result of previous line.

Page 10: Lecture9 recursion

Lets incorporate this Lets incorporate this previous process of backward going previous process of backward going into an algorithm as follows……..into an algorithm as follows……..

Page 11: Lecture9 recursion

#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().

Page 12: Lecture9 recursion

Above code reflects recursive algorithm of Above code reflects recursive algorithm of n!.n!. In this function is first called by main( ) In this function is first called by main( ) and then it calls and then it calls itselfitself until it calculates the until it calculates the n! and finally return it to main( ).n! and finally return it to main( ).

Page 13: Lecture9 recursion

Efficiency of RecursionEfficiency of Recursion In general, a non recursive version of a In general, a non recursive version of a

program will execute more efficiently in program will execute more efficiently in terms of terms of timetime and and spacespace than a recursive than a recursive version. This is because the overhead version. This is because the overhead involved in involved in enteringentering and and exitingexiting a a new new blockblock ( system stack )( system stack ) is avoided in the non is avoided in the non recursive version.recursive version.

However, sometimes a recursive solution is However, sometimes a recursive solution is the most the most naturalnatural and and logicallogical way of solving way of solving a problem as we will soon observe while a problem as we will soon observe while studying different studying different TreeTree data structuresdata structures..

Page 14: Lecture9 recursion

TreesTrees

Page 15: Lecture9 recursion

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 AliAli

There are a number of applications where linear There are a number of applications where linear data structures are not appropriate. Consider a data structures are not appropriate. Consider a genealogy (family tree) tree of a family.genealogy (family tree) tree of a family.

Page 16: Lecture9 recursion

Tree Data Structure Tree Data Structure A A linear linked listlinear linked list will not be able to will not be able to

capture the tree-like relationship with capture the tree-like relationship with ease. ease.

Shortly, we will see that for Shortly, we will see that for applications that require applications that require searchingsearching, , linear data structures are not suitable. linear data structures are not suitable.

We will focus our attention on We will focus our attention on binary binary treestrees. .

Page 17: Lecture9 recursion

Theorem:Theorem: A A TreeTree with with nn vertices vertices ( nodes )( nodes )

has has n-1n-1 edgesedges..

Page 18: Lecture9 recursion

Binary Tree Binary Tree

Page 19: Lecture9 recursion

A A Binary TreeBinary Tree is a finite set of elements is a finite set of elements that is either empty or is partitioned into that is either empty or is partitioned into threethree disjoint subsets. The disjoint subsets. The firstfirst subset subset contains a single element called a contains a single element called a rootroot of of the tree. The the tree. The other twoother two subsets are subsets are themselves binary trees, called the themselves binary trees, called the leftleft and and rightright sub trees of the original tree. sub trees of the original tree.

A A leftleft or or rightright sub tree can be sub tree can be emptyempty..

Each element of a Each element of a binary treebinary tree is called a is called a nodenode of the tree. of the tree.

Page 20: Lecture9 recursion

Following is an example of Following is an example of binary treebinary tree. This . This tree consists of tree consists of ninenine nodes with nodes with AA as its root. as its root. Its Its leftleft sub tree is rooted at sub tree is rooted at BB and its and its rightright sub sub tree is rooted at tree is rooted at CC..

AA

BB

GG

EE

IIHH

FF

CC

DD

Figure 1Figure 1

Page 21: Lecture9 recursion

Binary Tree Binary Tree

Page 22: Lecture9 recursion

The The absenceabsence of a branch indicates any of a branch indicates any empty sub empty sub treetree. For example in previous figure, the . For example in previous figure, the leftleft sub sub tree of the tree of the binary treebinary tree rooted at rooted at CC is is emptyempty..

Figures below shows that are Figures below shows that are notnot Binary Trees Binary 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

Page 23: Lecture9 recursion

If If AA is the root of binary tree and is the root of binary tree and BB is the is the root of its root of its leftleft or or rightright sub tree, then sub tree, then AA is said is said to be to be fatherfather oror parentparent of of BB and and BB is said to is said to be be leftleft or or rightright sonson ( ( childchild ) of ) of AA..

A node that has no child ( son ) is called A node that has no child ( son ) is called leafleaf..

Node Node n1n1 is an is an ancestorancestor of node of node n2n2 ( and ( and n2n2 is a is a descendentdescendent of of n1n1 ) if ) if n1n1 is either the is either the parentparent of of n2n2 or the parent of or the parent of somesome ancestorancestor of of n2n2. For example in previous . For example in previous Figure 1Figure 1 AA is an is an ancestorancestor of of GG and and HH is a is a descendentdescendent of of CC, but , but EE is neither a is neither a descendentdescendent nor nor ancestorancestor of of CC..

Page 24: Lecture9 recursion

If If every non leaf nodeevery non leaf node in a binary tree has non in a binary tree has non empty left and right sub trees, the tree is empty left and right sub trees, the tree is termed as termed as strictly binary treestrictly binary tree. Following . Following Figure Figure 44 is strictly binary tree while is strictly binary tree while Figure 1Figure 1 is not. is not.

A A strictly binary treestrictly binary tree with with nn leaves always leaves always contain contain 2n – 12n – 1 nodes. nodes.

AA

BB

DD

GG

EE

FF

CC

Figure 4Figure 4

Page 25: Lecture9 recursion

The The levellevel of a node in a binary tree is defined as of a node in a binary tree is defined as follows follows :->:-> The The rootroot of the tree has of the tree has level 0level 0, and , and the level of any other node in the tree is the level of any other node in the tree is one moreone more than the level of its than the level of its parentparent. For example in . For example in Figure Figure 11 node node EE is at is at level 2level 2 and node and node HH is at is at level 3level 3..

The The depthdepth of a binary tree is the of a binary tree is the maximum levelmaximum level of any of any leaf leaf in the tree. Thus depth of in the tree. Thus depth of Figure 1Figure 1 is is 33..

A A 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 except each level of the tree is completely filled except possibly the bottom level, and in this level the possibly 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,

Page 26: Lecture9 recursion

Complete Binary Tree Complete Binary Tree A A complete binary treecomplete binary tree of depth of depth dd is the is the

strictly Complete binarystrictly Complete binary if all of whose leaves if all of whose leaves are at level are at level dd. .

Page 27: Lecture9 recursion

Complete Binary Tree Complete Binary Tree A A complete binary treecomplete binary tree of depth of depth dd is the is the strictly strictly

binarybinary all of whose leaves are at level all of whose leaves are at level dd. .

Page 28: Lecture9 recursion

AA

BB

DD GGEE FF

CC

Strictly Complete Binary TreeStrictly Complete Binary TreeAA

BB

DD GGEE FF

CC

Complete Binary TreeComplete Binary Tree

HHAA

BB

DD FFEE

CC

Not Complete Binary TreeNot Complete Binary Tree

Page 29: Lecture9 recursion

Another common property is to Another common property is to traversetraverse a a binary tree i.e. to pass through the tree, binary tree i.e. to pass through the tree, i.e. enumerating or visiting each of its i.e. enumerating or visiting each of its nodes once.nodes once.

Page 30: Lecture9 recursion

Thank You……Thank You……