diff --git a/hutool-core/src/main/java/cn/hutool/core/tree/TreeUtil.java b/hutool-core/src/main/java/cn/hutool/core/tree/TreeUtil.java index 9c1dd2748..06853e18e 100644 --- a/hutool-core/src/main/java/cn/hutool/core/tree/TreeUtil.java +++ b/hutool-core/src/main/java/cn/hutool/core/tree/TreeUtil.java @@ -236,4 +236,89 @@ public class TreeUtil { public static Tree createEmptyNode(final E id) { return new Tree().setId(id); } + + /** + * 深度优先,遍历森林,将森林转换为数组 + * + * @param forest 森林 + * @param 节点ID类型 + * @return 森林所有节点列表 + */ + public static List> deepFirstForestConvertToList(List> forest) { + if (CollectionUtil.isEmpty(forest)) { + return null; + } + List> list = new ArrayList<>(); + forest.forEach(root -> list.addAll(Objects.requireNonNull(deepFirstTreeConvertToList(root)))); + return list; + } + + /** + * 广度优先,遍历森林,将森林转换为数组 + * + * @param forest 森林 + * @param 节点ID类型 + * @return 森林所有节点列表 + */ + public static List> broadFirstForestConvertToList(List> forest) { + if (CollectionUtil.isEmpty(forest)) { + return null; + } + List> list = new ArrayList<>(); + forest.forEach(root -> list.addAll(Objects.requireNonNull(broadFirstTreeConvertToList(root)))); + return list; + } + + + /** + * 深度优先,遍历树,将树换为数组 + * + * @param root 树的根节点 + * @param 节点ID类型 + * @return 树所有节点列表 + */ + public static List> deepFirstTreeConvertToList(Tree root) { + if (Objects.isNull(root)) { + return null; + } + + // 入栈,FILO + List> list = new ArrayList<>(); + Stack> stack = new Stack<>(); + stack.add(root); + while (!stack.isEmpty()) { + Tree node = stack.pop(); + list.add(node); + if (node.hasChild()) { + node.getChildren().forEach(stack::push); + } + } + return list; + } + + /** + * 深度优先,遍历树,将树转换为数组 + * + * @param root 树的根节点 + * @param 节点ID类型 + * @return 树所有节点列表 + */ + public static List> broadFirstTreeConvertToList(Tree root) { + if (Objects.isNull(root)) { + return null; + } + + // 加入FIFO队列 + List> list = new ArrayList<>(); + Queue> queue = new LinkedList<>(); + queue.offer(root); + while (!queue.isEmpty()) { + Tree node = queue.poll(); + list.add(node); + if (node.hasChild()) { + node.getChildren().forEach(queue::offer); + } + } + return list; + } }