SUNY Geneseo Department of Computer Science
Tree Traversals, Part 2
{Date}
CSci 240, Spring 2007
Prof. Doug Baldwin
Return to List of Lectures
Previous Lecture
Misc
SOFIs
Lab 11 (tree height) due today
Questions?
Tree Traversals
Process (e.g., print) all nodes in a tree
// In class BinaryTree<E>
private E root
private BinaryTree<E> left, right
traverse() {
if ( ! this.isEmpty() ) {
left.traverse() n1 elements
process root constant time
right.traverse() n2 elements
}
}
Kinds of traversal
- Preorder = root before children
- Inorder = root between children
- Postorder = root after children
Section 13.3.2
- Basics of traversals
- Proofs that traversal algorithm really works
- Visits every node
- Never visits a node twice
- Therefore traverse makes exactly n visits for n-node
tree, so Θ(n) time
Can you do a more rigorous derivation of execution time?
- Recurrence
- C(n) = 0 if n = 0
- C(n) = C(n1) + C(n2) + 1 if n > 0
where n1 + n2 = n - 1 and n1, n2 ≥ 0
- Patterns
- C(0) = 0
- C(1) = C(0) + C(0) + 1 = 1
- C(2) = C(0) + C(1) + 1 = 2
- Prove C(n) = n, by induction on n
- Base case, n = 0, C(0) = 0 from recurrence
- Induction hypothesis: assume C(j) = j, for all 0 ≤ j < k
- Show C(k) = k
- C(k) = C(k1) + C(k2) + 1, k1 + k2 = k - 1
- = k1 + k2 + 1 by induction hypothesis
- = k - 1 + 1
- = k
Uses of traversals
- Pre-order: push information down tree
- In-order: to process ordered trees in order
- Post-order: pull information up a tree (e.g., height)
Lab
Hand out Lab 12
Dictionary data structure
- Translates keys into values
- Search, insert, delete
- Implemented by lists, ordered trees, hash tables, etc.
Next
Priority queues and heaps
Read...
- Section 14.4 intro (pp 493 bottom to 494)
- 14.4.1 (pg 494)
- 14.4.4 up to but not including "Insertion" (pp 497 bottom
to 500 top)
Next Lecture