01: /**
02:    This class implements a binary search tree whose
03:    nodes hold objects that implement the Comparable
04:    interface.
05: */
06: public class Tree
07: {  
08:    /**
09:       Constructs an empty tree.
10:    */
11:    public Tree()
12:    {  
13:       root = null;
14:    }
15:    
16:    /**
17:       Inserts a new node into the tree.
18:       @param obj the object to insert
19:    */
20:    public void insert(Comparable obj) 
21:    {  
22:       Node newNode = new Node();
23:       newNode.data = obj;
24:       newNode.left = null;
25:       newNode.right = null;
26:       if (root == null) root = newNode;
27:       else root.insertNode(newNode);
28:    }
29:    
30:    /**
31:       Prints the contents of the tree in sorted order.
32:    */
33:    public void print()
34:    {  
35:       if (root != null)
36:          root.printNodes();
37:    }
38:   
39:    private Node root;
40: 
41:    /**
42:       A node of a tree stores a data item and references
43:       of the child nodes to the left and to the right.
44:    */
45:    private class Node
46:    {  
47:       /**
48:          Inserts a new node as a descendant of this node.
49:          @param newNode the node to insert
50:       */
51:       public void insertNode(Node newNode)
52:       {  
53:          if (newNode.data.compareTo(data) < 0)
54:          {  
55:             if (left == null) left = newNode;
56:             else left.insertNode(newNode);
57:          }
58:          else
59:          {  
60:             if (right == null) right = newNode;
61:             else right.insertNode(newNode);
62:          }
63:       }
64: 
65:       /**
66:          Prints this node and all of its descendants
67:          in sorted order.
68:       */
69:       public void printNodes()
70:       {  
71:          if (left != null)
72:             left.printNodes();
73:          System.out.println(data);
74:          if (right != null)
75:             right.printNodes();
76:       }
77:    
78:       public Comparable data;
79:       public Node left;
80:       public Node right;
81:    }
82: }
83: 
84: 
85: