使用此问题中提供的数据递归创建 TreeView?

Recursive TreeView creation with the data provided in this question?

我有一个 Treeview TreeView<MyType>,我想从 MyType 根 object 递归填充它。 class MyType 的结构如下:

public class MyType {

    private Set<MyType> children = new HashSet<>();

    public Set<MyType> getChildren() {
        return children;
    }

    public void setChildren(Set<MyType> children) {
        this.children = children;
    }

}

所以如你所见,MyType root/parent 有相同类型的 children,那些 children 也可以有 children 来自同一类型。实际上,根和它的最远继承者之间的深度不超过 1000 级。

我想用与数据存储在 MyType 根文件中相同的树结构中的树项 TreeItem<MyType> 递归地填充 Treeview TreeView<MyType>

这是我迄今为止尝试过的方法,但它不起作用:

void buildTree(MyType parent, TreeItem<MyType> result) {
    for (MyType child : parent.getChildren()) {
        if (child.getChildren() == null || child.getChildren().isEmpty()) {
            result.getChildren().add(new TreeItem<MyType>(child));
        }

        else {
            TreeItem<MyType> tmp = new TreeItem<>(child);
            buildTree(child, tmp);
        }
    }
}

是否可以使用提供的数据结构进行填充?

好的,我刚刚弄明白了。这按预期工作。

void buildTree(MyType parent, TreeItem<MyType> result) {
        for (MyType child : parent.getChildren()) {
            if (child.getChildren() == null || child.getChildren().isEmpty()) {
                result.getChildren().add(new TreeItem<MyType>(child));
            }

            else {
                TreeItem<MyType> tmp = new TreeItem<>(child);
                buildTree(child, tmp);
                result.getChildren().add(tmp);
            }
        }
    }

比较方便

一个。 Return TreeItems 而不是将 MyTypeTreeItem 都传递给递归方法调用。

乙。将叶子视为终端案例,而不是在叶子的父级处理终端案例

这允许您编写以下代码:

private TreeItem<MyType> buildSubtree(MyType root) {
    TreeItem<MyType> result = new TreeItem<>(root);

    if (root.getChildren() != null) {
        for (MyType child : root.getChildren()) {
            result.getChildren().add(buildSubtree(child));
        }
    }

    return result;
}