/**
* 把嵌套树结构 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
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.