深度优先和广度优先的区别:
代码如下(示例):
public class MainUtil2 {
public static void main(String[] args) throws Exception {
// 获取demo 数据
List<AuthMenuTree> list = getList();
// 变为树
List<AuthMenuTree> res = getChildrenStream(0, list);
System.out.println(JSONUtil.toJsonStr(res));
}
private static List<AuthMenuTree> getChildrenStream(int i, List<AuthMenuTree> list) {
return list.stream().filter(authMenuTree -> authMenuTree.getMenuPid() == i)
.peek(authMenuTree -> authMenuTree.setChildren(getChildrenStream(authMenuTree.getId(), list)))
.collect(Collectors.toList());
}
public static List<AuthMenuTree> getList() {
List<AuthMenuTree> objects = CollectionUtil.newArrayList();
objects.add(new AuthMenuTree(0, 1));
objects.add(new AuthMenuTree(1, 2));
objects.add(new AuthMenuTree(1, 3));
objects.add(new AuthMenuTree(2, 4));
objects.add(new AuthMenuTree(2, 5));
objects.add(new AuthMenuTree(3, 6));
objects.add(new AuthMenuTree(3, 7));
return objects;
}
}
代码如下(示例):
public static void main(String[] args) throws Exception {
// 获取demo 数据
List<AuthMenuTree> list = getList();
// 变为树
List<AuthMenuTree> res = getChildrenStream(0, list);
List<String> result = new ArrayList<>(res.size());
AuthMenuTree root = res.get(0);
// 深度优先 用栈
Stack<AuthMenuTree> stack = new Stack<>();
AuthMenuTree head;
// 入栈
stack.add(root);
// 出栈
while (!stack.isEmpty() && (head = stack.pop()) != null) {
if (!ObjectUtils.isEmpty(head.getChildren())) {
// 子类入栈
stack.addAll(head.getChildren());
}
// 添加到顺序结果集中
result.add(head.getId().toString());
}
System.out.println(JSONUtil.toJsonStr(result));
}
打印结果: [“1”,“3”,“7”,“6”,“2”,“5”,“4”]
代码如下(示例):
public static void main(String[] args) throws Exception {
// 获取demo 数据
List<AuthMenuTree> list = getList();
// 变为树
List<AuthMenuTree> res = getChildrenStream(0, list);
List<String> result = new ArrayList<>(res.size());
AuthMenuTree root = res.get(0);
// 广度优先 用队列
Queue<AuthMenuTree> treeQueue = new LinkedList<>();
AuthMenuTree head;
treeQueue.offer(root);
while ((!treeQueue.isEmpty()) && (head = treeQueue.poll()) != null) {
if (!ObjectUtils.isEmpty(head.getChildren())) {
treeQueue.addAll(head.getChildren());
}
result.add(head.getId().toString());
}
System.out.println(JSONUtil.toJsonStr(result));
}
打印结果: [“1”,“2”,“3”,“4”,“5”,“6”,“7”]
深度优先 用栈;广度优先 用队列;