Project

General

Profile

Download (1.94 KB) Statistics
| Branch: | Tag: | Revision:
1
package eu.etaxonomy.cdm.common;
2

    
3
import java.util.ArrayList;
4
import java.util.List;
5

    
6
//import eu.etaxonomy.cdm.model.location.TdwgAreaTest.NamedAreaTree;
7

    
8
public class Tree<T> {
9
	 
10
	private TreeNode<T> rootElement;
11
     
12
    /**
13
     * Default ctor.
14
     */
15
    public Tree() {
16
        super();
17
    }
18
 
19
    /**
20
     * Return the root TreeNode of the tree.
21
     * @return the root element.
22
     */
23
    public TreeNode<T> getRootElement() {
24
        return this.rootElement;
25
    }
26
 
27
    /**
28
     * Set the root Element for the tree.
29
     * @param rootElement the root element to set.
30
     */
31
    public void setRootElement(TreeNode<T> rootElement) {
32
        this.rootElement = rootElement;
33
    }
34
     
35
    /**
36
     * Returns the Tree<T> as a List of TreeNode<T> objects. The elements of the
37
     * List are generated from a pre-order traversal of the tree.
38
     * @return a List<TreeNode<T>>.
39
     */
40
    public List<TreeNode<T>> toList() {
41
        List<TreeNode<T>> list = new ArrayList<TreeNode<T>>();
42
        walk(rootElement, list);
43
        return list;
44
    }
45
     
46
    /**
47
     * Returns a String representation of the Tree. The elements are generated
48
     * from a pre-order traversal of the Tree.
49
     * @return the String representation of the Tree.
50
     */
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> element, List<TreeNode<T>> list) {
64
        list.add(element);
65
        for (TreeNode<T> data : element.getChildren()) {
66
            walk(data, list);
67
        }
68
    } 
69
}
(7-7/9)