-1

我有一个 PHP 示例用于我正在尝试执行的任务。如何使用 Java 做同样的事情?你能给我一个方向吗

function buildTree($array, $parent_id) {

    $arr = array();

    foreach ($array as $e) {

        if ($e['parent_id'] == $parent_id) {

            $arr[$e['id']] = array("title" => $e['title'],
                "id" => $e[$id],
                "children" => array());
            $submassive = buildTree($array, $e['id']);

            foreach ($submassive as $x) {
                $arr[$e['id']]['children'][] = $x;
            }
        }
    }

    return array_values($arr);
}
4

1 回答 1

1

Java 有 java.util.Map,您可以定义自己的 Node 类。

public class Node {
    public Integer id;
    public String title;
    public Integer parentId;
    public Node parent;
    public List<Node> children = new ArrayList<Node>();

    public Node(Integer id, String title, Integer parentId) {
        this.id = id;
        this.title = title;
        this.parentId = parentId;
    }

    public static Node buildTree(List<Something> things) {
        Map<Integer, Node> nodes = new HashMap<Integer, Node>();
        // step 1: create nodes and put them into a map.
        for (Something thing: things) {
            Node node = new Node(thing.id, thing.title, thing.parentId);
            nodes.put(node.id, node);
        }
        // Step 2: associate nodes with each other
        Node rootNode = new Node(null, "root", null)
        for (Node node: nodes.valueSet()) {
            if (node.parentId != null) {
                node.parent = nodes.get(node.parentId);
            } else {
                node.parent = rootNode;
            }
            node.parent.children.add(node);
        }
        return rootNode;
    }
}

顺便说一句:您的示例代码依赖于根本不需要的递归。首先创建一个映射/字典/关联数组,然后使用此映射构建树要简单得多。

于 2013-01-28T03:25:31.147 回答