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

D. Inorder Tree Traversal page 6 of 15

  1. At first glance, printing out the information in a binary tree, in ascending order, does not appear to be a simple task. The example diagram in Transparency AB30.1, Building a Binary Tree illustrates that the first node value printed should be 9, and getting there is fairly simple. The next value is 14, then 21. Then, there's a major issue - how do we get back to the root node whose value is 26? This is a backtracking problem that is elegantly solved using recursion.

  2. A tree traversal is an algorithm that visits every node in the tree. To visit a node means to process something regarding the data stored in the node. For now, visiting the node will involve printing the value object field.

  3. An inorder tree traversal visits every node in a certain order. Each node is processed in the following sequence.

    • Traverse the left subtree inorder
    • Visit node
    • Traverse the right subtree inorder

    Notice that actually visiting the node occurs between the two recursive calls.

  4. Here is the code for the inorder method.

    void inorder ( TreeNode temp )
    {
      if ( temp != null )
      {
        inorder ( temp.getLeft() );
        System.out.println( temp.getValue() );
        inorder ( temp.getRight() );
      }
    }

  5. To see how the method, inorder works, study the following table:
Step
Current Node Value
inorder is passed the root node
26
inorder is passed the left subtree of 26
14
inorder is passed the left subtree of 14
9
inorder is passed the left subtree of 9
null
Output 9
9
inorder is passed the right subtree of 9
null
Output 14
14
inorder is passed the right subtree of 14
21
inorder is passed the left subtree of 21
null
Output 21
21
inorder is passed the right subtree of 21
null
Output 26
26
inorder is passed the right subtree of 26
79
Continue processing

 

 

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