CS 46B - Lecture 24

Cover page image

Pre-class reading

Binary Search Trees

A Binary Search Tree

A Tree That is Not a BST

Insertion

Lecture 24 Clicker Question 1

Which tree is the result of inserting F R E D into an empty binary search tree

  1.    F
      / \
     D   R
      \
       E
  2.    F
        \ 
         R
        / 
       E
      /
     D
  3.     F
       / \
      E   R
     /  
    D   
  4. Something else

Implementation of Insertion

class Node
{
   . . .
   public void addNode(Node newNode)
   {
      int comp = newNode.data.compareTo(data);
      if (comp < 0)
      {
         if (left == null) { left = newNode; }
         else { left.addNode(newNode); }
      }
      else if (comp > 0)
      {
         if (right == null) { right = newNode; }
         else { right.addNode(newNode); }
      }
   }
   . . .
}

Finding an Element

Lecture 24 Clicker Question 2

Assume 1000 random integers were inserted into a BST. Approximately how many comparison are needed to find whether the integer 42 is among them?

  1. 1000
  2. 512
  3. 10
  4. 1

Removal

Removal

Lecture 24 Clicker Question 3

Consider this BST:

          C
         /  \
        A   G
           / \
          D   K

What is the result of removing C?

  1.      G
        / \
       A   K
          /
         D
  2.      A
          \
           G
          / \
         D   K
  3.      D
        / \
       A   G
            \
             K
  4. Someting else

Efficiency

Lecture 24 Clicker Question 4

You need to keep a set of lots of objects of class X. You don't care about traversal in sorted order, but you want maximum efficiency. What should you choose, and why?

  1. A hash table because its add/remove/find operations are O(1)+
  2. A re-balancing BST because its add/remove/find operations are guaranteed to be O(log n)
  3. A hash table because it is easier to come up with a hashCode method for X than a compareTo method
  4. A re-balancing BST because it is easier to come up with a compareTo method for X than a hashCode method