Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traverse to the deepest using Java

Tags:

java

loops

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?

like image 607
Malintha Avatar asked Sep 03 '13 11:09

Malintha


1 Answers

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)) { ... }
like image 75
ZhekaKozlov Avatar answered Oct 18 '22 20:10

ZhekaKozlov