0

我有一个 ArrayCollection,每个元素都是 TreeNode 类(我制作的自定义类)的一个实例,它有一个“children”属性,它是更多 TreeNode 元素的 ArrayCollection。这样,我在 ArrayCollection 结构中有一个元素树:

tree = new ArrayCollection([
    [new TreeNode(param1, param2, new ArrayCollection([
        [new TreeNode(param1, param2, null)],
        [new TreeNode(param1, param2, new ArrayCollection([
            [new TreeNode(param1, param2, null)],
            [new TreeNode(param1, param2, new ArrayCollection([
                [new TreeNode(param1, param2, null)],
                [new TreeNode(param1, param2, null)]
            ]))],
            [new TreeNode(param1, param2, new ArrayCollection([
                [new TreeNode(param1, param2, null)],
                [new TreeNode(param1, param2, null)]
            ]))]
        ]))]
    ]))],
    [new TreeNode(param1, param2, null)]
]);

TreeNode 构造函数有 3 个参数:前两个现在无关紧要,但第三个是 children 属性(一个 ArrayCollection),如果 TreeNode 没有任何子项,则该参数必须设置为 null。

我编写了以下函数来递归解析“树”结构:

private function parse(obj:Object):void {
    for (var i:int = 0; i < obj.length; i++) {
        if (obj[i] is TreeNode) {
            if (obj[i].children != null) {
                parse(obj[i].children);
            }
        } else {
            parse(obj[i]);
        }
    }
}
parse(tree);

但我的问题是:我需要有相同的“树”结构(它不需要是同一个变量)填充另一个类的实例。我怎样才能做到这一点?

4

1 回答 1

0

我做到了:

private function parse(obj:Object, ancestor:Node):void {
    for (var i:int = 0; i < obj.length; i++) {
        if (obj[i] is TreeNode) {

            var node:Node = new Node(obj[i].param1, obj[i].param2);
            node.ancestor = ancestor;

            if (ancestor != null) {
                ancestor.children.push(node);
            }

            if (obj[i].children != null) {
                parse(obj[i].children, node);
            }

            obj[i] = node;
        } else {
            parse(obj[i], ancestor);
        }
    }
}
parse(tree, null);

这样,所有的 TreeNodes 都将转换为 Nodes(Node 是我制作的另一个自定义类)

于 2011-02-02T10:57:14.740 回答