-
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.
-
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.
-
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.
-
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());
}
}
- To see how the method, inorder works, study the following table: