In Java, is Tree the best structure to represent a tree with such properties:
- all nodes are unique
ints; - the depth of a tree is given by
int d > 0 - there is no restriction on how many children a node could have
Operations I need todo:
- iterate over the children located on the first level down only of any node
- add nodes
- remove a subtree, that is a node with all its children all the way down
- extract a subtree, that is locate and copy (clone) in a separate tree
Operations I do not need:
- edit nodes
Properties are just perfect for a Tree, so maybe there is some super implementation available in terms of performance. XMLTree or whatever.
Currently I’m using an array of arrays to store elements, but I find it not subtle.
Here is a basic example of a
Nodeclass that could be used to form your tree structure. There is some complexity in writing methods to iterate over all child nodes in a depth-first or breadth-first fashion.As an alternative you could consider using
DefaultMutableTreeNodewhich provides these methods for free (depthFirstEnumeration(),breadthFirstEnumeration()). This node implementation also allows you to attach a user object by callingsetUserObject(Object). The drawback is that the implementation may not be as compact as writing your own structure, so it really depends on the size of your tree.