Using a Library Tree Class to Display a Hierarchy

Some Thoughts on Competitive Java

Many problems encountered in real life require the programmer to use a tree data structure as part of the solution. This is also true in many java competitions. Thus, a tree is probably the most important data structure to master ahead of any such competition. When the need for a tree arises, your first instinct will be to construct one. After all, building a basic tree is not difficult. But the problem with this approach is that writing and testing this basic tree code is time consuming - and time is not your friend in these competitions.

For these reasons, it is more efficient (time-wise) to make use of the existing Java libraries when possible. The downside to this approach is that students must familiarize themselves with the standard classes and their methods ahead of the competition. In this lesson, we deal with what is arguably one of the most important standard classes to master ahead of entering a java competition - Swing's DefaultMutableTreeNode. While it is true that the Swing Library is now out of date due to the emergence of JavaFX as a preferred GUI tool, the usefulness of this tree class remains because it can be used independent of the swing graphical user interface.

Before watching the video, below, that demonstrates how the DefaultMutableTreeNode class can be used to construct and display a tree (with or without Swing), look over the following important methods for this class listed below. For a more complete list of methods for this class, click here for Orcale's documentation on this important class.

Important Methods for DefaultMutableTreeNode:

DefaultMutableTreeNode(Object userObject)

Constructor: Creates a tree node with no parent, no children, but which allows children, and initializes it with the specified user object.

void add(MutableTreeNode newChild)

Removes newChild from its parent and makes it a child of this node by adding it to the end of this node's child array.

TreeNode getChildAt(int index)

Returns the child at the specified index in this node's child array.

int getChildCount()

Returns the number of children of this node.

int getLevel()

Returns the number of levels above this node -- the distance from the root to this node.

TreeNode getParent()

Returns this node's parent or null if this node has no parent.

Object getUserObject()

Returns this node's user object. In this lesson, these Objects will be Strings.

void remove(int childIndex)

Removes the child at the specified index from this node's children and sets that node's parent to null.

void setUserObject(Object userObject)

Sets the user object for this node to userObject.

How to Use Swing's DefaultMutableTreeNode Class



Project: Create a Hierarchical Map

You have been tasked with creating and printing a hierarchical map for biology. The list of living orgainisms are organized as "tuples" separated by a comma. (A "tuple" is a group of two items that are related to one another). The first item in each tuple contains the name of the sub-group or organism, while the second item contains the name of the group in which the item belongs. Your task is to take this flat list and convert it into a nested (hierarchical) view.

Input Rules

  • If the second item in the tuple is listed as "None", that means the first item is a root node.
  • There is only one root node; it is always the first record in the data
  • The number of levels in the hierarchy is unknown. Your program must handle input of many levels
  • All organism names are guaranteed to be unique
  • Parents will always appear in the input before any of their children

Example Input:

  • Animal Kingdom, None
  • Mammal, Animal Kingdom
  • Bird, Animal Kingdom
  • Amphibian, Animal Kingdom
  • Ostrich, Bird
  • Human, Mammal
  • Fish, Animal Kingdom
  • Robin, Bird
  • Salmon, Fish
  • Sockeye, Salmon
  • Gorilla, Mammal

Example Output:

The input, above, should result in the following output being created by your program:

  • Animal Kingdom
  • -Mammal
  • --Human
  • --Gorilla
  • -Bird
  • --Ostrich
  • --Robin
  • -Amphibian
  • -Fish
  • --Salmon
  • ---Sockeye

Hints: How to Read the Input Into Your Java Program

The java code segment below gives you an idea of how to load the input into your program. It does not reveal the solution, however. So any missing methods, you will have to write.  


import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.TreeNode;


public class BioHierarchy

 {

  public static void main(String args[]) {

      String [] [] input = {

          {"Animal Kingdom", "None"},

          {"Mammal", "Animal Kingdom"},

          {"Bird", "Animal Kingdom"},

          {"Amphibian", "Animal Kingdom"},

          {"Ostrich", "Bird"},

          {"Human", "Mammal"},

          {"Fish", "Animal Kingdom"},

          {"Robin", "Bird"},

          {"Salmon", "Fish"},

          {"Sockeye", "Salmon"},

          {"Gorilla", "Mammal"}          

        };

    

    DefaultMutableTreeNode root = new DefaultMutableTreeNode(input[0][0]);

    for (int i=1; i< input.length; ++i) {

        String nodeName = input[i][0];

        String parent = input[i][1];


        DefaultMutableTreeNode parentNode = locateParentNode(root, parent);

        parentNode.add(new DefaultMutableTreeNode(nodeName));

    }   

    printTree(root);


  }