首页 > 解决方案 > 使用此问题中提供的数据创建递归 TreeView?

问题描述

我有一个 Treeview TreeView<MyType>,我想从MyType根对象递归地填充它。类的结构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根/父级具有相同类型的子级,而这些子级也可以具有相同类型的子级。在实践中,根与其最远的继承者之间的深度不大于 1000 级。

我想用与存储在根文件中的数据相同的树结构中的TreeView<MyType>树项递归地填充 Treeview。TreeItem<MyType>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);
        }
    }
}

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

标签: javarecursionjavafxtreeview

解决方案


更方便

A. 返回TreeItems 而不是同时传递MyType和传递TreeItem给递归方法调用。

B. 将叶子视为绝症,而不是在叶子的父母处处理绝症

这允许您编写以下代码:

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;
}

推荐阅读