SUNY Geneseo Department of Computer Science


Tree Traversal

{Date}

CSci 141, Fall 2003
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture


Misc

Exam 2 next Wednesday (Nov. 19)

Questions?

Strong Induction and Trees

Count the nodes in a tree:

    int size() {
        if ( this.isEmpty() )
            return 0
        else
            return 1 + this.left().size()
                     + this.right().size()

How many primitive tree messages?

Recurrence relation for messages, f(), in terms of number of nodes, n

Find a closed form

Prove this by strong induction on n

Traversal

Traversal = visiting every node in a data structure in order to do something with it

e.g., compute a tree's height

Hint: height is precisely defined as follows:

    height()
        if ! this.isEmpty()
            leftHeight = this.left().height()
            rightHeight = this.right().height()
            if leftHeight > rightHeight
                return 1 + leftHeight
            else
                return 1 + rightHeight
        else
            return 0

Mini-assignment: work out efficiency of the above version of "height" vs one that sends "height" messages wherever it needs left or right subtree heights

Postorder traversal - visit subtrees first, then root

Also preorder, in-order

Next

Inserting new items into a binary search tree


Next Lecture