1 需求
旧版本xmind是xml格式, 11版本后变成json格式, 但数据层级一致
输出如下层级数据的全路径
节点A0
|---节点B01
|---|---节点C011
|---|---节点C012
|---节点B02
|---|---节点C021
|---|---|---节点D0211
2 样例数据
{
"title": "节点A0",
"children": [
{
"title": "节点B01",
"children": [
{
"title": "节点C011",
"children": []
},
{
"title": "节点C012",
"children": []
}
]
},
{
"title": "节点B02",
"children": [
{
"title": "节点C021",
"children": [
{
"title": "节点D0211",
"children": []
}
]
}
]
}
]
}
3 java代码
整体思路有点类似于汉诺塔
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Stack;
public class App {
public static void main(String[] args) throws IOException {
InputStream is = App.class.getClassLoader().getResourceAsStream("dag.json");
ObjectMapper mapper = new ObjectMapper();
Node root = mapper.readValue(is, Node.class);
Stack<Node> leftStack = new Stack<>();
Stack<List<Node>> rightStack = new Stack<>();
leftStack.push(root);
rightStack.push(root.getChildren());
while ( !leftStack.isEmpty()) {
List<Node> rightNodes = rightStack.peek();
if (rightNodes != null && rightNodes.size() > 0) {
// 右栈内容不为空, 将节点左移
Node moveLeftNode = rightNodes.remove(0);
leftStack.push(moveLeftNode);
rightStack.push(moveLeftNode.getChildren());
continue;
} else {
// 右栈内容为空时, 表示已遍历到末尾
// 提取左栈内容, 拼接形成完整路径
String text = "";
for (Node n: leftStack) {
text += n.getTitle() + " -> ";
}
if (text.length() > 0) text = text.substring(0, text.length() - 4);
System.out.println(text);
}
// 输出完成后, 执行去栈操作
while (true) {
if (!rightStack.isEmpty() && (rightStack.peek() == null || rightStack.peek().size() == 0)) {
rightStack.pop();
leftStack.pop();
continue;
}
break;
}
}
}
}
import java.util.List;
public class Node {
private String title;
private List<Node> children;
public Node() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Node> getChildren() {
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
}
输出结果
节点A0 -> 节点B01 -> 节点C011
节点A0 -> 节点B01 -> 节点C012
节点A0 -> 节点B02 -> 节点C021 -> 节点D0211