类别 - 子类遍历算法

时间:2014-04-30 05:41:52

标签: java algorithm

我正在寻找遍历类别列表以创建层次结构的好方法。我正在使用的当前算法将无法考虑深度嵌套。

我有一个所有类别的列表(包括父类及其所有子类别),类别类如下:

class Category{
     private int id;
     private int parentCategoryId;
     private String name;

     /*Getter Setters*/
}

此处parentCategoryId存储其父级的id,根类别将包含parentCategoryId = 0,并且它们可以是多个根类别。目前的情况要求我将嵌套扩展到至少5-6级深度,而我现在的算法就失败了。

有什么可能是一个很好的方式来按照这样的顺序排列它们,我可以在我的视图中轻松地迭代它们来构建这样的东西:

-Root1
--Root1Sub1
--Root1Sub2
---Root1Sub2SubSub1
---Root1Sub2SubSub2
-Root2
--Root2Sub1

1 个答案:

答案 0 :(得分:0)

您要查找的算法称为Depth-first search, or DFS(您还可以将其与Breadth-first search, BFS进行比较)。

正如维基百科所写:

  

深度优先搜索(DFS)是用于遍历或搜索树或图数据结构的算法。一个从根开始(在图的情况下选择一些任意节点作为根)并在backtracking之前尽可能地沿着每个分支进行探索。

为了有效地使用它,你的类需要有一个对子类别的引用列表(父ID不重要,但你应该有子类别的实际引用,而不是ID)。

算法(使用显式堆栈)就像:

static void dfs(Category root) {

    Stack stack = new Stack();

    // start by pushing the root node to the stack
    stack.push(root);

    while (!stack.isEmpty()) {

        Category node = (Category)stack.pop();

        // do something with this node
        // e.g. System.out.print(node.name);

        // push children to the stack
        stack.addAll(node.children);
    }
}

递归解决方案更简单:

static void recursiveDfs(Category node) {

    // do something with this node
    // e.g. System.out.print(node.name);

    // recursively process all children
    Iterator children = node.children.iterator();
    while (children.hasNext())
        recursiveDfs((Category)children.next());
}