I have a data structure like below:
Task(id,name,subTasks[Task])
But the problem is the subTasks can contain Tasks which have another subTa
Use Guava TreeTraverser:
Task root = ...
/*
* For example, you have the following tree:
*
* h
* / | \
* / e \
* d g
* /|\ |
* / | \ f
* a b c
*/
TreeTraverser<Task> traverser = new TreeTraverser<Task>() {
@Override
public Iterable<Task> children(Task root) {
return root.subTasks;
}
};
Then you can iterate over the tree with for
loop in several ways:
// Iterate in breadth-first order (hdegabcf)
for (Task task : traverser.breadthFirstTraversal(root)) { ... }
or
// Iterate in preorder (hdabcegf)
for (Task task : traverser.preOrderTraversal(root)) { ... }
or
// Iterate in postorder (abcdefgh)
for (Task task : traverser.postOrderTraversal(root)) { ... }
Data structure: the implicit tree formed by object references.
Traversal: recursion or queues.
However, you will have to consider each use case individually. Some will call for depth-first traversal, some for breadth-first traversal. Consider using some graph library to build the trees in the first place if you need a lot of graph operations.