Skip to main content
ICT
Lesson AB30 - Binary Search Trees
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

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.