chapter five recursion and trees l.
Skip this Video
Loading SlideShow in 5 Seconds..
Chapter Five Recursion and Trees PowerPoint Presentation
Download Presentation
Chapter Five Recursion and Trees

Loading in 2 Seconds...

play fullscreen
1 / 37

Chapter Five Recursion and Trees - PowerPoint PPT Presentation

  • Uploaded on

Chapter Five Recursion and Trees. Recursion Divide and conquer Dynamic programming Trees and tree traversals Graphs and graph traversals Please read chapter 5. Recursive algorithms. What’s the runtime of this algorithm? int puzzle(int N) { if (N == 1) return 1;

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'Chapter Five Recursion and Trees' - susanna

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
chapter five recursion and trees
Chapter FiveRecursion and Trees
  • Recursion
  • Divide and conquer
  • Dynamic programming
  • Trees and tree traversals
  • Graphs and graph traversals

Please read chapter 5.

recursive algorithms
Recursive algorithms
  • What’s the runtime of this algorithm?

int puzzle(int N)


if (N == 1) return 1;

if (N % 2 == 0) return puzzle(N/2);

else return puzzle(3 * n + 1);


Why is it hard to determine the runtime?

Recursive algorithms need base case and

recursive call(s) (preferably smaller!)

euclid s algorithm
Euclid’s algorithm
  • Suppose you write a first-class Fraction class
  • Need to reduce fractions, such as 546/3185
  • Note that gcd(m,n) = gcd(n,m%n)




gcd(91,0) return 91

 return 91

 return 91

 return 91


int gcd(int m, int n) {

if (n == 0) return m;

return gcd(n, m%n);


  • What is a fractal?

self-similarity at a different level

/kochR {

2 copy ge {dup 0 rlineto }


3 dif

2 copy kockR

60 rotate

2 copy kochR

-120 rotate

2 copy kochR

60 rotate

2 copy kochR

} ifelse

pop pop

} def

Koch Snowflake: how to draw?

0 0 moveto

27 81 kochR

0 27 moveto

9 81 kochR

0 54 moveto

3 81 kochR

0 81 moveto

1 81 kochR


2D Fractal Star…

Fractal flowers…

divide and conquer
Divide and Conquer
  • Split a problem into smaller subproblems
  • Solve the subproblems recursively
  • Merge the subproblem solutions into a solution to the whole problem

The great point is to learn to solve a problem in

terms of subproblem solutions.

divide and conquer examples
Divide and Conquer Examples
  • Merge sort
  • Binary Search
  • Towers of Hanoi
  • Parsing HTML, XML
  • pow(x,n)
  • log(n,base)
  • log*(n)
  • Point-in-convex-polygon
min max
Min & Max
  • Given a set of n items, find the min and max. How many comparisons needed?
  • Simple alg: n-1 comparisons to find min, n-1 for max
  • Recursive algorithm:

void minmax(int i, int j, int& min0, int& max0)

if (j<=i+1) [handle base case; return]




min0 = min(min1,min2);

max0 = max(max1,max2);


T(n)=2T(n/2) + 2; T(2)=1


1.5 n - 2

  • How long does it take to multiply two n-bit numbers?
  • Grade school algorithm:



  • Recursive algorithm:

How to solve in terms of subproblem solutions?

(a 2n/2 + b)(c 2n/2 + d)

ac 2n + (ad + bc)2n/2 + bd

T(n) = 4T(n/2) + c n




(a+b)(c+d) = ac + ad + bc + bd

T(n)=3T(n/2) + c n

O(nlg 3)

fibonacci numbers
Fibonacci Numbers
  • What is the Golden ratio?
  • Can approximate with Fibonacci numbers.
  • Mi to km conversion
  • Pineapple raster, pine cone pattern…
  • Recursive Fibonacci algorithm?
  • Runtime Recurrence?

T(1)=1; T(2)=1; T(n) = T(n-1) + T(n-2) + 1

  • Runtime?

not sure…but at least W(2n/2)

  • How to improve runtime?
    • compute bottom-up
    • or just remember values you’ve already computed
dynamic programming
Dynamic Programming
  • Solve by combining solutions to overlapping subproblems
  • Runtime of recursive solution is typically exponential
  • Make the algorithm efficient:
    • built a table bottom-up
    • or memoize
dp example making change
DP Example: Making Change
  • Making change
    • Available coin values: v1, v2, v3, …, vk
    • How to make change totalling C with fewest coins?
    • Base cases: mincoins(0)=0; mincoins(v1)=1, etc.
    • Recursive step:

mincoins(n)=min[ 1+mincoins(n-v1),

1+mincoins(n-v2), …, 1+mincoins(n-vk) ]

  • Runtime recurrence?
  • How to make this algorithm efficient?
    • table-based approach
    • memoization
algorithm design by dynamic programming
Algorithm design byDynamic Programming
  • Identify subproblem solutions of interest.Name them.
  • Express solution to whole problem recursively,in terms of subproblem solutions
  • Memoize (or compute bottom-up)

coin values v1, v2, …, vn

mincoins(k)=smallest number of coins to totaling k in value

mincoins(k) = 1 if k = vi, infinity if k < 1

mincoins(k) = min[mincoins(k-v1), …, mincoins(k-vn) ] + 1

jot down subproblem solutions as you compute them

dp example weird dice
DP Example: Weird Dice
  • Given several weird dice. Roll probabilities?
    • Dice have s1, s2, s3, …, sn sides
    • Count the number of ways you can roll each roll; divide by Psk
    • Base case: rolling die number 1.
    • What about 2 dice, 3, …?
    • Subproblem solutions of interest?
    • Rolls(n,i) = number of ways of rolling n with first i dice

=Rolls(n-1, i-1) + Rolls(n-2,i-1) + … + Rolls(n-sk,i-1)

    • Rolls(i,1) = 1,
    • Runtime?

O(S sk)

= O(n) if sk <= const.

  • You are robbing a bank vault. How to maximize take?
  • Items 1, 2, …, n have values v1, v2, …, vn and integer weights w1, w2, …, wn
  • How to maximize take, if you can only carry B lbs?
  • Subproblems of interest:

maxval(w,k) = best value with weight w, objects a subset of 1..k

  • Recursive solution?

maxval(w,k) =

max[maxval(w-1,k),maxval(w,k-1), maxval(w-wk,k-1)+vk]

maxval(w,0) = 0

want maxval(B,n)

  • memoize or compute bottom up
other dynamic programming applications
Other Dynamic Programming applications
  • Not-one strategies
  • Shortest path
  • Paragraph wrapping
  • Matrix chain multiplication
  • Polygon triangulation
  • lots of optimization problems…
graphs and trees
Graphs and Trees
  • Graph:

a set V of vertices (or nodes) and a set E of edges, a subset of VxV

  • Digraph:

a graph with directed edges

  • Tree:

a connected, acyclic graph with one node designated as root

  • Sibling, parent, ancestor, descendent
  • External node:

“dummy” node or null pointer

  • Leaf:

a node with only external nodes as children

binary trees
Binary Trees
  • Path:

a list of connected vertices

  • Height of a rooted tree:

the length of the longest path from the root to a leaf

  • Binary tree:

a tree where each node has up to 2 children, called “left” and “right”

  • Complete binary tree:

a tree where all the leaves are at the same level

  • Binary search tree (BST):

a binary tree where the key of any node is greater than the keys of the nodes in its left subtree and less than those of its right subtree.

tree properties and traversals
Tree Properties and Traversals
  • How many edges in a tree of n nodes?


  • How many external nodes in a tree of n nodes?


  • Height of a binary tree with n nodes?

between lg n and n-1

  • How can I visit every node of a tree?
  • Traversals:
    • preorder
    • inorder
    • postorder
parse trees
Parse Trees
  • How would one parse an arithmetic expression?
  • Parse tree:
    • a node for each operator
    • leaves for operands
  • Parse tree traversals:
    • What does inorder traversal give?

infix expression: (3+4)*(5-6)

    • Postorder?

postfix expression: 3 4 + 5 6 – *

    • Preorder?

prefix expression: * + 3 4 – 5 6

non recursive traversals
Non-recursive Traversals
  • How to implement a traversal non-recursively?
  • What kind of traversal is this:

void traverse(link n, void visit(link))


STACK<link> s(max);


while (!s.empty())


visit(n = s.pop());

if (n->right != 0) s.push(n->right);

if (n->left != 0) s.push(n->left);



graph traversals
Graph Traversals
  • How do you find your way out of a maze, given a large supply of pennies?
  • Graph traversals
    • Depth-first search
    • Breadth-first search
  • Other applications: Boggle™, tic-tac-toe, path finding, theorem proving, motion planning, AI, …
representing a graph
Representing a Graph

Two different drawings of the same graph are shown.

  • What data structure to represent this graph?
adjacency matrix
Adjacency Matrix


A 1 1 0 0 1 1 0 0 0 0 0 0

B 0 0 0 0 0 0 0 0 0 0 0

C 0 0 0 0 0 0 0 0 0 0

D 1 1 0 0 0 0 0 0 0

E 1 1 0 0 0 0 0 0

F 0 0 0 0 0 0 0

G 0 0 0 0 0 0

H 1 0 0 0 0

I 0 0 0 0

J 1 1 1

K 0 0

L 1


Space required for a graph

with v vertices, e edges?


Time to tell if there is an

edge from v1 to v2?


adjacency list
Adjacency List

A: F -> B -> C -> G

B: A

C: A

D: E -> F

E: D -> F -> G

F: D -> E

G: A -> E

H: I

I: H

J: K -> L -> M

K: J

L: M -> J

M: J -> L

Space required for a graph with v vertices, e edges?


Time to tell if there is an edge from v1 to v2?


depth first search
Depth-first Search

Main idea: keep traveling to a new,

unvisited node until you you get stuck.

Then backtrack as far as necessary and try a new path.

dfs recursive
DFS: Recursive
  • How to implement recursively?

void dfs(link n, void visit(link))




for (link t=adj[k]; t!=0; t = t->next)

if (!visited[t->v]) dfs(t->v, visit);




O(e+v) for e edges, v vertices


O(v) – a path may be really long

dfs non recursive
DFS: Non-recursive
  • How can you implement DFS non-recursively?
  • Use a stack

void dfs(link h, void visit(link))


STACK<link> s(max);


while (!stack.empty())

if (!visited[n = s.pop()])


visit(n); visited[n]=1;

for (link t=adj[n]; t!=0; t=t->next)

if (visited[t->v] == 0) s.push(t->v);




breadth first search
Breadth-first Search
  • Breadth-first search:

Visit all neighbors of the start node

(but don’t visit a node you’ve already seen).

Then all neighbors of theirs,

and of theirs,






breadth first search30
Breadth-first search
  • How can you implement BFS?
  • Use a queue with the DFS algorithm!

void bfs(link h, void visit(link))


QUEUE<link> q(max);


while (!q.empty()])

if (!visited[n = s.pop()])


visit(n); visited[n]=1;

for (link t=adj[n]; t!=0; t=t->next)

if (visited[t->v] == 0) s.push(t->v);




aside on ai
Aside on AI
  • Will computers ever be intelligent?
  • Really intelligent?
  • Tasks that previously were thought to require intelligence:
    • adding and subtracting
    • playing chess
    • driving a car
    • recognizing speech or handwriting
    • translating to a foreign language
    • proving mathematical theorems
  • What does it mean to say that a computer is intelligent?
  • Is that the same as being a person? What is a person?
  • Is a computer program a person?
  • Is a person a computer program?
achieving intelligence
Achieving “Intelligence”
  • How do AI program achieve “intelligent” behavior?
  • Currently, three main paradigms:
    • Symbolic knowledge representation and search
    • Neural Nets
    • Genetic Algorithms
search in artificial intelligence
Search in Artificial Intelligence
  • Represent your problem as a graph where nodes are states and edges are operators that go between states
    • Define problem states (nodes)
    • Identify start and goal states
    • Define operators (edges)
    • Use DFS or BFS to find goal
  • Example: Missionaries and cannibals problem
    • states: (3,3,1)  3 missionaries, 3 cannibals, and 1 boat on left side of river.
    • Operators: one or two people cross the river in the boat, so that there isn’t a cannibal majority on either side.
    • Goal: get to the other side?
    • Moves?
    • (331)–(220)–(321)–(210)–(221)–(020)–(031)–(010)–(021)–(000)
dfs bfs resource requirements
DFS/BFS Resource Requirements
  • DFS:
    • Runtime?

O(n), n=number of nodes expanded

    • Space required?

O(d), d = depth of search

    • Can I cut off a search after 5 seconds?
  • BFS:
    • Runtime? O(n)
    • Space required?

O(breadth of tree) = O(bd), b=branching factor

    • Can I cut off a search after 5 seconds?
  • Staged DFS: do a DFS of depth 1, 2, 3, … until out of time
    • Runtime?


    • Space required? O(d)
game playing
Game Playing
  • We could use DFS but…can’t search whole tree!
    • limit depth of search and use an evaluation function
  • We could use DFS but…how do we know which move the opponent will choose?
    • minimax algorithm: assume the opponent does what looks best.
    • i.e. at nodes where it is the human’s turn, pick the move that looks best for human. Where computer’s turn, pick the move that looks best for the computer
  • An ancient gamed called Kalah or Mankalah uses stones and pits: 6 to a side and one on each end.
  • 4 stones are initially placed in each side pit. None are in the end pits (called Kalahs – a player’s kalah is on her right).
  • A move consists of picking up the stones in a pit and distributing them, one at a time, in successive pits.
    • If the last stone is placed in your Kalah, you go again
    • If the last stone is placed in an empty pit on your side, you capture the stones in that pit and the opposite one, on the opponent’s side of the board. These are put into your Kalah.
  • The game ends when one player has no stones left; the other player puts all the remaining stones on her side into her Kalah.
  • Whoever ends with more stones in her Kalah wins.
  • See the demo program on holmes at /home/hplantin/kalah.c

 Write a smart kalah playing program!

mankalah minimax
Mankalah minimax

int kalahboard::minimax(depth d): //semi-pseudocode

if [human won] return –infinity;

if [machine won] return +infinity;

if (d==0) return evaluate();

if (whosemove==HUMAN)


for (move=first; move<=last; move++)

kalahboard b=*this; //duplicate board

if (b.board[move]>0) //is move legal?

b.makemove(move); //make the move

v=b.minimax(d-1); //find its value

if (v<best) best=v; //remember if best

else // similarly for MACHINE’s move

return best;