SUNY Geneseo Department of Computer Science


Introduction to Trees

{Date}

CSci 141, Spring 2004
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture


Questions?

insertValue turns empty tree into non-empty

[Replacing Parts of a Tree]

    Tree t1 = new Tree()
    t1.addItem(...)
    ....
    Tree t2 = t1.left()
    t1.insertValue( x )

Stack Wrap-Up

One example of why stacks are so important

Recursion, e.g.,

    printParens( int n ) 
        if n > 0
            print "("
            printParens( n-1 )
            print ")"

Trace some invocations in "printParens(3)"

LIFO is exactly how methods call and return

Introduction to Trees

Read sections 13.1, 13.2, 13.4

("Unary tree" = list)

Examples of trees in real life

Parts of trees

Properties

[Nodes with Arbitrary Edges between Them]

Trees in CS

            if answer1 = "yes"
                ask question 2
                if answer2 = "yes"
                    ask question 3
                    ....
                else
                    ask question 3a
                    if answer 3a = yes
                        ....

[A Tree with Questions]

        askQuestions()
            print this.question
            read answer
            if answer = yes
                this.left().askQuestions()
            else
                this.right().askQuestions()

If-then-else as trees?

    main() {
        x = 1
        for ( i= 1; i < 10 ; i++ ) {
            z = 17
            if i < 5
                y = 3
                x = x +1
            else
                print "hello"
            q = 9
        }  
    }

[Nested Control Structure as a Tree]

Trees as data structures

Trees are recursively defined

Ordered tree class

Some Tree Algorithms

Mini-Assignment:

Count the nodes in a tree

    // In a subclass of OrderedTree
    int countNodes()
        ...

Next Lecture