SUNY Geneseo Department of Computer Science


Tree Deletion and Traversal

{Date}

CSci 240, Spring 2007
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture

Misc

GREAT Day

SOFIs

Lab 11 (tree height) due Wednesday

Questions?

Ordered Binary Tree Deletion

Make the code a bit cleaner

    // In class OrderedTree<E>
    private E root;
    private OrderedTree<E> left, right;

    OrderedTree<E> delete( E value ) {
        if ( ! this.isEmpty() ) {
            if ( root == value ) {
                return this.actualDelete()
            }
            else if ( value > root ) {
                right = right.delete( value )
                return this
            }
            else {
                left = left.delete( value )
                return this
            }
        }
        else {
            return this
        }
    }

    OrderedTree<E> actualDelete() {
        if ( left.isEmpty() ) {
            return right
        }
        else if ( right.isEmpty() ) {
            return left
        }
        else {
            // copy largest value in left to this, and remove
            // that largest node in left
            secondLargest = this
            node = this.left
            while ( node.hasRight() ) {
                secondLargest = node
                node = node.right
            }
            this.root = node.root
            if ( secondLargest == this ) {
                this.left = node.left
            }
            else {
                secondLargest.right = node.left
            }
            return this
        }
    }
[Finding a Node's Largest Left Descendant]

What are the execution times for deletion from an ordered binary search tree?

Tree Traversals

Goal: Process (e.g., print) all nodes in a tree

What might a traversal algorithm look like?

        // In class BinaryTree<E>
        private E root
        private BinaryTree<E> left, right

        traverse() {
            if ( ! this.isEmpty() ) {
                left.traverse()
                process root
                right.traverse()
            }
        }

Kinds of traversal

Next

Finish traversals, maybe start heaps and priority queues

Read section 13.3.2


Next Lecture