Java Reference
In-Depth Information
L ISTING 25.6
TestBST.java
1 public class TestBST {
2 public static void main(String[] args) {
3 // Create a BST
4 BST<String> tree = new BST<>();
5 tree.insert( "George" );
6 tree.insert( "Michael" );
7 tree.insert( "Tom" );
8 tree.insert( "Adam" );
9 tree.insert( "Jones" );
10 tree.insert( "Peter" );
11 tree.insert( "Daniel" );
12
13 // Traverse tree
14 System.out.print( "Inorder (sorted): " );
15 tree.inorder();
16 System.out.print( "\nPostorder: " );
17 tree.postorder();
18 System.out.print( "\nPreorder: " );
19 tree.preorder();
20 System.out.print( "\nThe number of nodes is " + tree.getSize());
21
22 // Search for an element
23 System.out.print( "\nIs Peter in the tree? " +
24
create tree
insert
inorder
postorder
preorder
getSize
tree.search( "Peter" ));
search
25
26 // Get a path from the root to Peter
27 System.out.print( "\nA path from the root to Peter is: " );
28 java.util.ArrayList<BST.TreeNode<String>> path
29 = tree.path( "Peter" );
30 for ( int i = 0 ; path != null && i < path.size(); i++)
31 System.out.print(path.get(i).element + " " );
32
33 Integer[] numbers = { 2 , 4 , 3 , 1 , 8 , 5 , 6 , 7 };
34 BST<Integer> intTree = new BST<>(numbers);
35 System.out.print( "\nInorder (sorted): " );
36 intTree.inorder();
37 }
38 }
Inorder (sorted): Adam Daniel George Jones Michael Peter Tom
Postorder: Daniel Adam Jones Peter Tom Michael George
Preorder: George Adam Daniel Michael Jones Tom Peter
The number of nodes is 7
Is Peter in the tree? true
A path from the root to Peter is: George Michael Tom Peter
Inorder (sorted): 1 2 3 4 5 6 7 8
The program checks path != null in line 30 to ensure that the path is not null before
invoking path.get(i) . This is an example of defensive programming to avoid potential
runtime errors.
The program creates another tree for storing int values (line 34). After all the elements are
inserted in the trees, the trees should appear as shown in FigureĀ 25.9.
If the elements are inserted in a different order (e.g., Daniel, Adam, Jones, Peter, Tom,
Michael, George), the tree will look different. However, the inorder traversal prints elements
in the same order as long as the set of elements is the same. The inorder traversal displays a
sorted list.
 
 
Search WWH ::




Custom Search