CIT 594 Assignment 1: Tree API
Spring 2009, David Matuszek
A tree is a data structure composed of nodes, where each node contains a value of some arbitrary type, and a list of zero or more children, each of which is also a node. In this data structure, essentially each node is a tree.
In this assignment you are to build a simple Tree API. This API will enable you to create trees, read and write trees, and do basic navigation.
This will be a genericized class--that is, when you construct a tree, you specify the type of values it can hold.
public class Tree<V> {...}public Tree<V>(V value)
(Eliminate the <V> here)ArrayList to hold its
(future) children.public Tree<V> addChild(Tree<V> child) throws IllegalArgumentExceptionchild as the new last child of this Tree.
equals) also written.
IllegalArgumentException until
after you have written and tested the contains method. Once
that is done, come back and modify this method to throw the exception when
tree1.addChild(tree2) is called, and tree2.contains(tree1).
This would create a loop, or cycle, in the Tree, which is illegal.
public Tree<V> addChild(V value) throws IllegalArgumentExceptionaddChild(new Tree(value)).@Override
public boolean equals(Object obj) false if the Object is not a Tree.
equals method),
and they have the same number of children
and all their children are equal and in the same
order.
@Override
public String toString()value(child_1 child_2 ... child_N)2 and '2') can have the same String
representation.public List<Tree<V>> children()public Iterator<Tree<V>> iterator()public void setValue(V value)public V getValue()public static
Tree<V><String> parse(String s)StringTokenizer
to get "tokens" from the input string. Use the settingsnew StringTokenizer(s, " ()", true)
parse method. This method should do something
approximately as follows:
Get a value for the root (or return null)
If there is an open parenthesis,
Parse each tree inside the parentheses and add it to the root
Get the close parenthesis
Return the treepublic void print()public boolean contains(Tree<V> tree)== sense)
node as the given tree.
This method should also be recursive.| Given this Tree: | toString() should return:one(two three(four five(six seven eight))) |
![]() |
print() should print: |
DS01 (dee-ess-zero-one)supportclass Tree
public Tree<V>(V value) // constructor @Override public boolean equals(Object obj)@Override public String toString()public Tree addChild(Tree child) throws IllegalArgumentExceptionpublic Tree addChild(V value) throws IllegalArgumentExceptionpublic List children()Iterator<Tree<V>> iterator()public void setValue(V value)public V getValue()public Tree<V> parse(String)public void print()public boolean contains(Tree<V> tree)DS01_yourName The above are requirements. You may have additional classes and methods as needed, and they should be documented and unit tested as appropriate.
Thursday, January 22, before midnight. Zip the complete Eclipse project and submit via Blackboard.