Skip to main content
ICT
Lesson AB30 - Binary Search Trees
 
Main   Previous Next
 

G. Searching a Binary Tree page 9 of 15

  1. Searching an ordered binary tree can be solved iteratively or recursively. Here is the iterative version:

    TreeNode find( TreeNode root, Comparable valueToFind )
    {
      TreeNode node = root;

      while (node != null)
      {
        int result = valueToFind.compareTo( node.getValue() );
        if ( result == 0 )
          return node;
        else if ( result < 0 )
          node = node.getLeft();
        else  // if (result > 0)
          node = node.getRight();
      }
      return null;
    }

  2. If the value is not in the tree, the node pointer will eventually hit a null.

  3. Notice the type of the argument, valueToFind, in the find method is designated as Comparable. find’s code calls the compareTo method of the valueToFind object to determine the ordering relationship. We declare valueToFind as a Comparable, not just an Object to guarantee that it will have a compareTo method.

  4. A recursive version is left for you to implement as part of Lab Assignment AB30.2, BS Tree continued.

  5. The order of searching an ordered binary tree is O(log2N) for the best case situation. For a perfectly balanced tree, the capacity of each level is 2level #.

    Level #

    0
    1
    2
    3
    4
    5
    etc.

    Capacity of Level

    1
    2
    4
    8
    16
    32

    Capacity of Tree

    1
    3
    7
    15
    31
    63


  6. So starting at the root node, a tree of 63 nodes would require a maximum of 5 left or right moves to find a value. The number of steps in searching an ordered binary tree is approximately O(log2N).

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.