The document discusses recursion and binary trees. It defines recursion as a function that calls itself, directly or indirectly. A recursive function must have a base case and recursively break the problem into smaller subproblems until the base case is reached. Binary trees are discussed as a data structure where each node has at most two children. Properties of binary trees like the root, left and right subtrees, ancestors and descendants are explained. Complete and strictly binary trees are defined, where a complete binary tree fills each level except possibly the last.
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..
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.