Java Reference
In-Depth Information
If you add lines to this diagram, you'll see the tree:
1
2
3
4
5
6
7
8910 11 12 13 14 15
The output has the root node between its two subtrees, so this traversal is a varia-
tion of the inorder traversal. Oddly enough, you want to print the right subtree before
the left subtree. For example, consider the following tree:
7
6
5
Your method would produce the following output:
5
7
6
Notice that the right subtree value of 5 is printed first, then the root, then the left
subtree value of 6 . This happens because you are rotating the image.
You can fairly easily modify your inorder traversal code to produce this new set of
methods:
public void printSideways() {
printSideways(overallRoot);
}
private void printSideways(IntTreeNode root) {
if (root != null) {
printSideways(root.right);
System.out.println(root.data);
printSideways(root.left);
}
}
But this version of the code does not indent the various levels of the tree. To obtain
the proper indentation, you need to introduce an extra parameter to let the private
method know the level at which each node appears. The initial call on the private
method should pass the value 0 because the overall root should be indented 0 spaces.
 
Search WWH ::




Custom Search