# JAVA树形数据结构的实现

ryan
• 19

## 已知数据结构

``````[
"测试/测试/测试2",
"工单/问题反馈309",
"工单/问题反馈565",
"工单/问题反馈54",
"工单/问题反馈310",
"测试专用/123456/test/123"
]``````

``````测试
测试
测试2

问题反馈309
问题反馈565
问题反馈54
问题反馈310

123456
test
123``````

4 个回答

### 实现代码

``````import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

/**
* @author ryan
* @version \$Id Test.java, v 0.1 2019-10-14 10:21 ryan Exp \$
*/
public class Test {
public static void main(String[] args) {
String[] arrays = new String[] { "测试/测试1/测试2", "工单/问题反馈309", "工单/问题反馈565", "工单/问题反馈54",
"工单/问题反馈310", "测试专用/123456/test/123" };

Node node = new Node("root");

for (String array : arrays) {
List<Node> eachList = null;
for (String str : array.split("/")) {
if (eachList == null) {
eachList = node.getSubNodeList();
}
eachList = buildSubNode(str, eachList);
}
}

System.out.println(JSON.toJSONString(node));

}

/**
* 构建子节点
*
* @param nodeName 节点名称
* @param subNodeList 子节点集合
* @return 子节点
*/
private static List<Node> buildSubNode(String nodeName, List<Node> subNodeList) {
// 如果已经存在
for (Node node : subNodeList) {
if (node.getName().equals(nodeName)) {
return node.getSubNodeList();
}
}

Node node = new Node(nodeName);
return node.getSubNodeList();
}

static class Node {
private String name;

List<Node>     subNodeList = new ArrayList<Node>();

Node(String name) {
this.name = name;
}

/**
* Getter method for property <tt>name</tt>.
*
* @return property value of name
*/
public String getName() {
return name;
}

/**
* Setter method for property <tt>name</tt>.
*
* @param name value to be assigned to property name
*/
public void setName(String name) {
this.name = name;
}

/**
* Getter method for property <tt>subNodeList</tt>.
*
* @return property value of subNodeList
*/
public List<Node> getSubNodeList() {
return subNodeList;
}

/**
* Setter method for property <tt>subNodeList</tt>.
*
* @param subNodeList value to be assigned to property subNodeList
*/
public void setSubNodeList(List<Node> subNodeList) {
this.subNodeList = subNodeList;
}
}
}``````

### 打印结果

``{"name":"root","subNodeList":[{"name":"测试","subNodeList":[{"name":"测试1","subNodeList":[{"name":"测试2","subNodeList":[]}]}]},{"name":"工单","subNodeList":[{"name":"问题反馈309","subNodeList":[]},{"name":"问题反馈565","subNodeList":[]},{"name":"问题反馈54","subNodeList":[]},{"name":"问题反馈310","subNodeList":[]}]},{"name":"测试专用","subNodeList":[{"name":"123456","subNodeList":[{"name":"test","subNodeList":[{"name":"123","subNodeList":[]}]}]}]}]}``