Java Reference
In-Depth Information
It then prints the traversals as follows:
The pre-order traversal is: C E F H B G A N J K
The in-order traversal is: F H E B C A G J N K
The post-order traversal is: H F B E A J K N G C
The buildTree method is not restricted to single-character data; any string (not containing whitespace since we
use %s to read the data) can be used.
For example, if btree.in contains this:
hat din bun @ @ fan @ @ rum kit @ @ win @ @
then Program P8.1 builds the following tree:
hat
din
rum
bun
fan
kit
win
It then prints the traversals as follows:
The pre-order traversal is: hat din bun fan rum kit win
The in-order traversal is: bun din fan hat kit rum win
The post-order traversal is: bun fan din kit win rum hat
In passing, note that the in-order and pre-order traversals of a binary tree uniquely define that tree. It's the same
for in-order and post-order. However, pre-order and post-order do not uniquely define the tree. In other words, it is
possible to have two different trees A and B where the pre-order and post-order traversals of A are the same as the pre-
order and post-order traversals of B, respectively. As an exercise, give an example of two such trees.
8.6 Binary Search Trees
Consider one possible binary tree built with the three-letter words shown in Figure 8-3 .
ode
lea
tee
era
mac
ria
vim
Figure 8-3. Binary search tree with some three-letter words
 
Search WWH ::




Custom Search