递归遍历菜单树
```java
/**
* @author admin
* @date 2022/8/2
*/
public class TreeUtil {
/**
* 创建树结构
* @param regionTrees
* @return
*/
private List<RegionTree> tree(List<RegionTree> regionTrees) {
//返回的节点树
List<RegionTree> rootNodes = new ArrayList<>();
Iterator<RegionTree> it = regionTrees.iterator();
while (it.hasNext()) {
RegionTree next = it.next();
//parent(上级Id)为0的是根节点
if ("0".equals(next.getParentId())) {
rootNodes.add(next);
it.remove();
}
}
//遍历,找到二级节点
for (RegionTree regionTree : rootNodes) {
List<RegionTree> child = getChild(regionTrees, regionTree.getId().toString());
regionTree.setChildren(child);
}
return rootNodes;
}
/**
* 查子节点
*
* @param regions
* @param parentId
* @return
*/
private List<RegionTree> getChild(List<RegionTree> regions, String parentId) {
//子节点列表
List<RegionTree> childList = new ArrayList<>();
Iterator<RegionTree> it = regions.iterator();
while (it.hasNext()) {
RegionTree regionTree = it.next();
if (parentId.equals(regionTree.getParentId())) {
childList.add(regionTree);
it.remove();
}
}
//遍历 递归获取子节点的子节点
for (RegionTree regionTree : childList) {
List<RegionTree> child = getChild(regions, regionTree.getId().toString());
regionTree.setChildren(child);
}
//递归出口 childList长度为0
if (childList.size() == 0) {
return new ArrayList<>();
}
return childList;
}
}
```