I have a data structure like below:
Task(id,name,subTasks[Task])
But the problem is the subTasks can contain Tasks which have another subTasks. This can run to very deep like this:
Task1 Contains SubTask1
SubTask1 contains it's sub tasks
and you can understand this can be run to very deep.
I can retrieve these data from a database tables. But how can I store this in a data structure in java. Using for loops without knowing the deep is useless and not a elegant way. What would be the best data structure and data traversal way?
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)) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With