樹實體類
public class Node {
private int id;//結(jié)點id
private int pid;//父結(jié)點id
private String name;//結(jié)點值
private List<Node> children = new ArrayList<>();//孩子結(jié)點列表
private Node parent;
private int level;
public Node(int id,int pid,String name){
this.id = id;
this.pid = pid;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Node> getChildren() {
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public boolean isRoot() {
return parent == null;
}
public boolean isLeaf() {
return children.size() == 0;
}
}
樹結(jié)構(gòu)排序工具類
public class TreeHelper {
public static List<Node> getSortedNodes(List<Node> datas) {
List<Node> result = new ArrayList<>();
// 設(shè)置Node間父子關(guān)系
List<Node> nodes = convertData2Node(datas);
// 拿到根節(jié)點
List<Node> rootNodes = getRootNodes(nodes);
// 排序以及設(shè)置Node間關(guān)系
for (Node node : rootNodes) {
addNode(result, node, 0);
}
return result;
}
private static List<Node> convertData2Node(List<Node> nodes) {
for (int i = 0; i < nodes.size(); i++) {
Node n = nodes.get(i);
for (int j = i + 1; j < nodes.size(); j++) {
Node m = nodes.get(j);
if (m.getPid() == n.getId()) {
n.getChildren().add(m);
m.setParent(n);
} else if (m.getId() == n.getPid()) {
m.getChildren().add(n);
n.setParent(m);
}
}
}
return nodes;
}
private static List<Node> getRootNodes(List<Node> nodes) {
List<Node> root = new ArrayList<>();
for (Node node : nodes) {
if (node.isRoot())
root.add(node);
}
return root;
}
private static void addNode(List<Node> nodes, Node node, int currentLevel) {
node.setLevel(currentLevel);
nodes.add(node);
if (node.isLeaf())
return;
for (int i = 0; i < node.getChildren().size(); i++) {
addNode(nodes, node.getChildren().get(i), currentLevel + 1);
}
}
}
測試類
public class Test {
public static void main(String[] args) {
List<Node> nodes = new ArrayList<>();
nodes.add(new Node(1, 0, "組織架構(gòu)"));
nodes.add(new Node(2, 1, "黨委a"));
nodes.add(new Node(3, 1, "黨委b"));
nodes.add(new Node(4, 2, "a支部1"));
nodes.add(new Node(5, 2, "a支部2"));
nodes.add(new Node(6, 2, "a支部3"));
nodes.add(new Node(7, 3, "b支部1"));
nodes.add(new Node(8, 3, "b支部2"));
nodes.add(new Node(9, 4, "b支部3"));
List<Node> list = TreeHelper.getSortedNodes(nodes);
for (Node node : list) {
for (int i = 0; i < node.getLevel(); i++)
System.out.print(" ");
System.out.println(node.getId() + " " + node.getName());
}
}
}
輸出結(jié)果
1 組織架構(gòu)
2 黨委a
4 a支部1
9 b支部3
5 a支部2
6 a支部3
3 黨委b
7 b支部1
8 b支部2
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者