JMU
Binary Search Trees
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Background
An Example

Using a Linked Structure

images/linked_bst.gif

Traversals

A preorder traversal of this BST will print the values in the nodes in the following order: 23, 15, 8, 12, 25, 24

A postorder traversal of this BST will print the values in the nodes in the following order: 12, 8, 15, 24, 25, 23

Searching with BSTs

A Recursive Algorithm

    search(current, target)
    {
      if (current == null)               print("Not present!")
      else if (current's data == target) print("Found!")
      else if (current's data >target) search(current's left, target)
      else                               search(current's right, target)
    }
  
Searching with BSTs (cont.)

A Non-Recursive Algorithm

    search(current, target
    {
      while ( (current != null) && (current's data != target) )
      {

          if (current's data > target) current = current's left
	  else                           current = current's right
      }

      if (current's data == target) print("Found!")
      else                          print("Not present!")
    }
  
Sorting with BSTs
Inserting Nodes into a BST
Inserting Nodes into a BST (cont.)

Ignoring Balance

    insert(current, n)
    {
      if (current == null)                    current = n;
      else if (n's data < current's data) insert(current's left,  n)
      else if (n's data > current's data) insert(current's right, n)
      else                                   print("Duplicate!")
    }
    
Removing Nodes from a BST
Removing Nodes from a BST (cont.)
Removing Nodes from a BST (cont.)