使用Java遍历最深处 [英] Traverse to the deepest using Java

查看:104
本文介绍了使用Java遍历最深处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下数据结构:

Task(id,name,subTasks[Task])

但问题是subTasks可以包含具有另一个子任务的任务。这可以像这样运行得非常深:

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包含它的子任务

SubTask1 contains it's sub tasks

你可以理解这可以运行得非常深。

and you can understand this can be run to very deep.

我可以从数据库表中检索这些数据。但是我如何将它存储在java中的数据结构中。在不知道深度的情况下使用for循环是无用的,而不是一种优雅的方式。什么是最好的数据结构和数据遍历方式?

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?

推荐答案

使用Guava TreeTraverser:

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)) { ... }

// Iterate in preorder (hdabcegf)
for (Task task : traverser.preOrderTraversal(root)) { ... }

// Iterate in postorder (abcdefgh)
for (Task task : traverser.postOrderTraversal(root)) { ... }

这篇关于使用Java遍历最深处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆