Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 类别-子类别遍历算法_Java_Algorithm - Fatal编程技术网

Java 类别-子类别遍历算法

Java 类别-子类别遍历算法,java,algorithm,Java,Algorithm,我正在寻找一种很好的方法来遍历类别列表,以创建层次结构。我目前使用的算法将无法考虑深度嵌套 我有一个所有类别的列表(包括父类别及其所有子类别),类别类别如下: class Category{ private int id; private int parentCategoryId; private String name; /*Getter Setters*/ } 在这里,parentCategoryId存储其父级的id,根类别将具有parentCat

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

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

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 --Root1Sub1 --根1子2 ---root1sub2sub1 ---root1sub2sub2 -根2 --Root2Sub1
您正在寻找的算法被称为(您也可以将其与之进行比较)

正如维基百科所写:

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

为了有效地使用它,您的类需要有一个对子类别的引用列表(父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());
}

发布您当前的算法,以便我们可以扩展它。它需要递归算法。你现在的是什么?