CS241: heaps!

  1. xkcd yesterday
  2. Binary tree methods: int ht(), int countRoots(), int countLeaves(), countInteriorNodes(), traverse() (preorder/inorder /postorder
  3. How to paint a tree (instead of printing it sideways)
    1. write void paint(Graphics g, int x, int y, int w, int h), or void paint(Graphics g, Rectangle r)
    2. if (!empty) // avoid infinite recursion
          draw the root in the middle, near the top
          left.paint(g, the rectangle which is the left half of the remainder of r, below the root)
          right.paint(g, the rectangle which is the right half of the remainder of r, below the root) 
                      
      Like this:
    3. Two Component methods JFrame inherits
      1. Rectangle getBounds()
      2. Insets getInsets()
  4. BSTs - what could go wrong? Comparing Objects? Degeneracy!
  5. Heaps - a solution to the worst case of a BST
    1. always has a near-delta shape (no degeneracy!)
    2. every root is <= both children's roots, thus the smallest element is at the root
  6. Heap methods
    1. insert
      	insert new element at the insertion point (first empty slot, to the right of the step on the near-delta)
      	swap up to it's proper place (to preserve heapness)
      	i.e.
      	if ! at root of heap
      		if it is < its parent (i.e. is out of place) {
      			swap roots with parent
      			recurse on parent
      		}	    	
                      
      running time?
    2. delete root
      	save the root (to return)
      	swap from rightmost, bottom row (to the left of the step on the near-delta) and trim the old root
      	swap the root down to the proper place
      	i.e.
      	if ! a leaf
      		if it is > either child (or just the left, if there's no right) {
      			swap roots with smaller child
      			recurse on that child
      		}	    	
                      
      running time?
  7. representation; an array!
  8. heapsort
    	for each element in the list
    		insert in the heap
    	list.clear();
    	while !heap.isEmpty()
    		list.add(heap.deleteRoot());