Data Structures AND Algorithms: Lecture Notes 9
Data Structures AND Algorithms: Lecture Notes 9
DATA STRUCTURES
AND
ALGORITHMS
Lecture Notes 9
Recursion
Spring 2008
3
return 1 + length(“ce”)
2
return 1 + length(“e”)
1
return 1 + length(“”)
0
fib1 = 1
fib2 = 1
# calls apparently
O(2n) – big!
Performance is O(n)
template<typename Item_Type>
int linear_search (
const std::vector<Item_Type>& items,
const Item_Type& target, size_t pos_first) {
if (pos_first == items.size()) return -1;
else if (target == items[pos_first])
return pos_first;
else
return linear_search(items, target, pos_first+1);
}
Problem Inputs
Number of disks (an integer)
Letter of starting peg: L (left), M (middle), or R (right)
Letter of destination peg (L, M, or R), but different from starting peg.
Letter of temporary peg (L, M, or R), but different from starting peg and destination peg.
Problem Outputs
A list of moves
Function Behavior
void show_moves(int n, char Builds a string containing all moves for a
start_peg, char dest_peg, chat game with n disks on start_peg that will
temp_peg) be moved to dest_peg, using temp_peg
for temporary storage of disks being moved.
printback(a,n)
Stack s;
s.push(a,n,0)
while s.notempty
a,n,i=s.pop()
if(n==0) continue
if(i==0)
s.push(a,n,i+1)
s.push(a+1,n-1,0)
else if(i==1) print(*a)
else ERROR
Recursive count:
int count(TreeNode *t)
{
int a=0;
if t==NULL return 0;
else{
a+=count(t->left);
a+=count(t->right);
a=a+1;
return a;
}
}