Recursion on Trees
CMPT 225
Recursion
Recursion: A definition of a function is recursive if the body cointains an application of itself.
Consider:
or
These two descriptions of 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
- -> S(4)
- returns 4+6=10
Iterative version:
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)
:
- Call 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
- We will often use recursion & induction on trees.
- e.g. the tree rooted a v has some property if its subtrees have some related property
- e.g. the height of node v in a binary tree may be defined by:
(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:
for the follwing tree:
-
v
-
a
-
e
- g
- h
-
f
- i
-
e
-
b
- c
- d
-
a
Recursion on Trees Example (pt 2)
(See math equation of previous slide)
h(v) = 3
-
v (3)
-
a (2)
-
e (1)
- g (0)
- h (0)
-
f (1)
- i (0)
-
e (1)
-
b (1)
- c (0)
- d (0)
-
a (2)
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
- A traversal of a graph is a process that “visits” each node in the graph once.
- We consider 4 standard tree traversalt:
- level order
- pre-order
- in-order
- post-order
- 2,3,4 begin at the root & recursively visit the nodes in each subtree & the root. They vary in the relative ???(can’t read).
(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.
- v is visited before any of its decendants
- every node in the left subtree is visited before any node in the right subtree.
Tree to come back to:
-
A
-
B
- D
- E
-
C
- F
-
B
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