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 >  
 

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.