Recursion on Trees

CMPT 225

Recursion

Recursion: A definition of a function is recursive if the body cointains an application of itself.

Consider: S(n)=i=0ni S(n)=\sum_{i=0}^{n} i

or

S(n)={0if n=0n+S(n1)if n>0 S(n) = \begin{cases} 0 & \text{if } n=0\\ n+S(n-1) & \text{if } n>0 \end{cases}

These two descriptions of S(n)S(n) suggest two implementations:

e.g.:

S(n){
  s=0
  for i=1..n
    s=s+i
  return s
}

or

S(n){
  if n=0
    return 0
  else
    return n+S(n-1)
}

Recursive Version

Iterative version:

S=0+i=1ni=1+i=2ni=3+i=3ni==0+1+2+3+4 S = 0 + \sum_{i=1}^{n} i = 1 + \sum_{i=2}^{n} i = 3 + \sum_{i=3}^{n} i = \dots\\ = 0+1+2+3+4

The same computation, but a different control strategy.

Recursion & The Call Stack

Code:

S(n){
  if(n=0){
    r=0
  }else{
    r=n+S(n-1)
  }
  return r
}

Compute p=S(2):

The call stack at the end:

Name Value Removed
S <code of S; n=0, r=0> true
S <code of S; n=1, r=1> true
S <code of S; n=2, r=3> true
p 3 false

After the call the S(2) is complete, the entire call stack of S to S to S is gone.

There are 2 more slides containing slightly different versions of the same diagrams. They do not provide any extra information.

Recursion on Trees

h(v)={0 if v is a leaf1+max{h(left(v)),h(right(v))} otherwise h(v) = \begin{cases} 0 & \text{ if v is a leaf}\\ 1 + \text{max}\{h(\text{left}(v)), h(\text{right}(v))\} & \text{ otherwise} \end{cases}

(We can define h(left(v)) to be -1 if left(v) does not exist, and sim. for right(v)).

Recurssion a Trees Examples

height of node v in T:

h(v)={0 if v is a leaf1+max{h(left(v)),h(right(v))} ow h(v) = \begin{cases} 0 & \text{ if v is a leaf}\\ 1+ max\{h(\text{left}(v)),h(\text{right}(v))\} & \text{ ow} \end{cases}

for the follwing tree: h(v)=?h(v)=?

Recursion on Trees Example (pt 2)

(See math equation of previous slide)

h(v) = 3

Pseudo-code version:

height(v){
  if v is a leaf
    return 0
  if v has one child u
    return 1+height(u)
  else
    return 1+max(height(left(v)), height(right(v)))
}

Traversals of Binary Tree

(Level order later)

Code:

pre-order-T(v){
  visit v
  pre-order-T(left(v))
  pre-order-T(right(v))
}

pre-order-T(v) does nothing if v does not exist.

Tree to come back to:

Pre-order-traversal: A,B,D,E,C,F

in-order-T

code:

in-order-T(v){
  in-order-T(left(v))
  visit v
  in-order-T(right(v))
}

In order traversal: D,B,E,A,C,F

post-order-T

code:

post-order-T(v){
  post-order-T(left(v))
  post-order-T(right(v))
  visit v
}

Post order traversal: D,E,B,F,C,A

End

…some repeated slides… unknown reason