SUNY Geneseo Department of Computer Science


Introduction to Heaps

{Date}

CSci 240, Spring 2007
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture

Misc

SOFIs

Questions?

Heaps

Read Section 14.4 intro (pp 493 bottom to 494)

Two kinds of heap

Examples

[A Complete Tree Heap]

Try to develop algorithm(s) for inserting a new value into a heap.

[Heap Containing 2, 3, 6, and 9]

    insert( v )
        make node from v
        make this node a leaf of heap, in available spot closest to root
        while v is less than parent (and v has a parent)
            swap with parent
    insert2( v )
        if ( ! this.isEmpty() )
            if ( v >= this.value )
                if ( putleft )
                    putleft = left.insert(v )
                    return true
                else 
                    putleft = ! right.insert( v )
                    return false
            else
                swap v with this.value
                this.insert( v )        // this is the old root value after swap
        else
            this.value = v; left = right = empty heap
            return false

First version of "insert" above is pretty solid, but requires finding the empty leaf position "closest to root." This is a well-defined notion if the heap is a "complete" tree.

[Tree with Top 3 Levels Filled and Left-Most 3 Nodes Present at Bottom]

Hand out Problem Set 13

Next

Representing complete trees

Read section 14.2.4


Next Lecture