[Recursion + Visitor Pattern] Realize the tree traversal processing of nodes

    /**
     * 把嵌套树结构 Tree 转成 Graph 图结构
     *
     * @param tree Tree
     * @return Graph
     */
    public static GraphVO tree2graph(ItemVO tree) {
        List<EdgeDO> edgeList = new ArrayList<>();
        buildEdges(tree, edgeList);
        final List<ItemVO> nodeList = new ArrayList<>();
        visitTree(tree, t -> {
            ItemVO node = new ItemVO();
            BeanUtils.copyProperties(t, node);
            // 图节点,children 置为空
            node.children = new ArrayList<>();
            nodeList.add(node);
        });
        GraphVO graph = new GraphVO();
        graph.setEdgeList(edgeList);
        graph.setItemList(nodeList);
        return graph;
    }


    /**
     * 访问者模式,递归遍历树节点
     *
     * @param t       树节点
     * @param visitor 访问者
     */
    private static void visitTree(ItemVO t, TreeVisitor visitor) {
        visitor.visit(t);
        if (null != t.children) {
            for (ItemVO child : t.children) {
                visitTree(child, visitor);
            }
        }
    }

Kotlin developer community

1233356-4cc10b922a41aa80

The public account of the first Kotlin developer community in China, which mainly shares and exchanges related topics such as Kotlin programming language, Spring Boot, Android, React.js / Node.js, functional programming, and programming ideas.

The more noisy the world, the more peaceful thinking is needed.

1665 original articles published · 1067 praised · 750,000 views

Guess you like

Origin blog.csdn.net/universsky2015/article/details/105175740