Go to the deepest with Java

I have a data structure as shown below:

Task(id,name,subTasks[Task]) 

But the problem is that subtasks can contain tasks that have other subtasks. This can be very deep:

 Task1 Contains SubTask1 

SubTask1 contains subtasks

and you can understand that it can be run very deeply.

I can get this data from database tables. But how can I save this in a data structure in java. Using for loops without knowledge of depth is useless and not elegant. What will be the best data structure and data path?

+4
source share
2 answers

Use Guava TreeTraverser:

 Task root = ... /* * For example, you have the following tree: * * h * / | \ * / e \ * dg * /|\ | * / | \ f * abc */ TreeTraverser<Task> traverser = new TreeTraverser<Task>() { @Override public Iterable<Task> children(Task root) { return root.subTasks; } }; 

You can then iterate over the tree using the 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)) { ... } 
+19
source

Data structure: an implicit tree formed by references to objects.

Workaround: recursion or queues.

However, you will have to consider each use case separately. Some of them will require a walk around the depth, and some will require a walk around the width. Consider using some graph library to create trees first if you need a lot of graph operations.

+3
source

Source: https://habr.com/ru/post/1500286/


All Articles