SUNY Geneseo Department of Computer Science


Tree Search and Insertion

{Date}

CSci 240, Spring 2007
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture

Questions?

Tree lab?

Building and Searching Trees

Sections 13.3.3 and 13.3.4

Our own examples

[Ordered Binary Tree]

Code

    class OrderedBinaryTree {                     // tree of ints
        private int root;                         // == -1 for empty tree
        private OrderedBinaryTree left, right;

    boolean isEmpty() {
        ...
    }

    int countOccurrences( int x ) {
        if ( ! this.isEmpty() ) {
            if ( x < root ) {
                return left.countOccurrences( x );
            }
            else if ( x == root ) {
                return right.countOccurrences( x ) + 1; }
            else {                                // x > root
                return right.countOccurrences( x );
            }
        }
        else {
            return 0;
        }
    }
	
    OrderedBinaryTree insert( int x ) {
        if ( ! this.isEmpty() ) {
            if ( x < root ) {
                left = left.insert( x );
                return this;
            }
            else {                                // x >= root
                right = right.insert( x )
                return this;
            }
        }
        else {
            return new OrderedBinaryTree( x );
        }
    }

Next

Efficiency of binary tree algorithms

Read Section 13.3.5


Next Lecture