public class TestGenerateSubTree{
public static void main(String[] args) {
TestGenerateSubTree testGenerateSubTree = new TestGenerateSubTree();
List<Node> nodeList = new ArrayList<>();
Node node1 = new Node("0",null);
Node node2 = new Node("1","0");
Node node3 = new Node("2","0");
Node node4 = new Node("3","1");
Node node5 = new Node("4","2");
nodeList.add(node1);
nodeList.add(node2);
nodeList.add(node3);
nodeList.add(node4);
nodeList.add(node5);
testGenerateSubTree.GetAllTreeByLoop1(nodeList);
}
public void GetAllTreeByLoop1(List<Node> nodeList){
List<Node> nodes = new ArrayList<>();
//找到所有的一级菜单
for(Node node : nodeList){
if(node.parent == "" || node.parent == null){
nodes.add(node);
}
}
//为一级菜单设置子菜单
for (Node node : nodes){
node.setChildren(getChildren(node.id,nodeList));
}
System.out.println(nodes.get(0).children.get(1).children.get(0).id);
}
private List<Node> getChildren(String id, List<Node> nodeList) {
List<Node> childList = new ArrayList<>();
for (Node node : nodeList){
if(node.parent != null && node.parent != "" && node.parent.equals(id)){
childList.add(node);
}
}
//递归遍历二级菜单及下面的子菜单
for (Node node : childList){
node.setChildren(getChildren(node.id,nodeList));
}
if(childList.size() == 0){
return null;
}
return childList;
}
}
class Node{
Node(String id,String parent){
this.id = id;
this.parent = parent;
}
String id;
String parent;
List<Node> children;
public void setChildren(List<Node> children) {
this.children = children;
}
}
递归生成目录树
最新推荐文章于 2023-08-08 18:07:37 发布