1
|
package eu.etaxonomy.cdm.common;
|
2
|
|
3
|
import java.util.ArrayList;
|
4
|
import java.util.List;
|
5
|
|
6
|
|
7
|
public class Tree<T,S> {
|
8
|
|
9
|
private TreeNode<T,S> rootElement;
|
10
|
|
11
|
/**
|
12
|
* Default ctor.
|
13
|
*/
|
14
|
public Tree() {
|
15
|
super();
|
16
|
}
|
17
|
|
18
|
/**
|
19
|
* Return the root TreeNode of the tree.
|
20
|
* @return the root element.
|
21
|
*/
|
22
|
public TreeNode<T,S> getRootElement() {
|
23
|
return this.rootElement;
|
24
|
}
|
25
|
|
26
|
/**
|
27
|
* Set the root Element for the tree.
|
28
|
* @param rootElement the root element to set.
|
29
|
*/
|
30
|
public void setRootElement(TreeNode<T,S> rootElement) {
|
31
|
this.rootElement = rootElement;
|
32
|
}
|
33
|
|
34
|
/**
|
35
|
* Returns the Tree<T> as a List of TreeNode<T,S> objects. The elements of the
|
36
|
* List are generated from a pre-order traversal of the tree.
|
37
|
* @return a List<TreeNode<T,S>>.
|
38
|
*/
|
39
|
public List<TreeNode<T,S>> toList() {
|
40
|
List<TreeNode<T,S>> list = new ArrayList<TreeNode<T,S>>();
|
41
|
walk(rootElement, list);
|
42
|
return list;
|
43
|
}
|
44
|
|
45
|
/**
|
46
|
* Returns a String representation of the Tree. The elements are generated
|
47
|
* from a pre-order traversal of the Tree.
|
48
|
* @return the String representation of the Tree.
|
49
|
*/
|
50
|
@Override
|
51
|
public String toString() {
|
52
|
return toList().toString();
|
53
|
}
|
54
|
|
55
|
/**
|
56
|
* Walks the Tree in pre-order style. This is a recursive method, and is
|
57
|
* called from the toList() method with the root element as the first
|
58
|
* argument. It appends to the second argument, which is passed by reference
|
59
|
* as it recurses down the tree.
|
60
|
* @param element the starting element.
|
61
|
* @param list the output of the walk.
|
62
|
*/
|
63
|
private void walk(TreeNode<T,S> element, List<TreeNode<T,S>> list) {
|
64
|
list.add(element);
|
65
|
for (TreeNode<T,S> data : element.getChildren()) {
|
66
|
walk(data, list);
|
67
|
}
|
68
|
}
|
69
|
}
|