Structural Recursion with a Tree

Exercise:

  1. Download Tree.java
  2. Experiment with it until you understand every aspect of the code.
  3. Create a tree using these interactions: createDemoTree.hist
    > Tree t10 = new Tree(10);     // creates a tree with no children
    > Tree t30 = new Tree(30);
    > Tree t20 = new Tree(20, t10, t30);     // creates a tree with 2 children
    > Tree t60 = new Tree(60);
    > Tree t70 = new Tree(70, t60, null);     // creates a tree with 1 child, a left child
    > Tree t50 = new Tree(50, null, t70);     // creates a tree with 1 child, a right child
    > Tree tree = new Tree(40, t20, t50);
    > tree.printTree();
    10  20  30  40  50  60  70
       
  4. Add a method called sumOfChildren which returns the sum of the integers in a tree's immediate left and right children (if they exist). These interactions should work:
    > t10.sumOfChildren()  
    0            
    > t70.sumOfChildren() 
    60         
    > tree.sumOfChildren()
    70
    
  5. Notice that the tree has the property that for each node, all the nodes to the left contain data smaller than the node's data. Likewise with larger items on the right. Binary trees that are ordered in this way are called binary search trees because their ordering makes it easy to search for items in them. Add a recursive method called min that assumes the tree is a binary search tree and returns the smallest data item in the tree. It should behave as shown below.
    > tree.min()
    10
    > t50.min()
    50
    > t70.min()
    60
    
  6. Think of other methods or changes to the code that might be useful to add, and implement them.