递归的优缺点
优点:言简意赅 容易读懂 实现起来比较容易
缺点:
1:时间/空间复杂度问题 时间复杂度计算公式 = 递归的次数 * 每次递归的时间/空间复杂度,递归算法的本质是自身调用自身,
每次的递归都需要在内存栈中分配参数的内存,每次在栈中数据的弹出和压入都需要时间,所以效率很低。
2:效率问题 在递归中许多运算是重复计算的 所以对计算性能造成很大影响
3.调用栈溢出:因为每一次方法调用都得在内存栈中分配空间,而每个进程的栈的容量是有限的。当一个递归方法不确定递归
层数时候调用的层级时,层级过多很大可能就会超出栈的容量,从而导致调用栈溢出。
递归方法展示
下面方法为一个目录平面结构到目录层级树的组装
public void buildTree(Map<Long, List<Tree>> parentMap, List<Tree> parentList) {
parentList.forEach(tree-> {
List<Tree> children = parentMap.get(tree.getId());
if(CollectionUtils.isNotEmpty(children)) {
tree.setChild(children);
buildCatalogList(parentMap, children);
}
});
}
循环队列方法代替递归方法
用队列循环代替递归方法调用
public void buildTree(Map<Long, List<Tree>> parentMap, List<Tree> parentList) {
Queue<Tree> queue = new LinkedList<>();
//将第一层级的目录全部入列
parentList.forEach(queue::offer);
while (!queue.isEmpty()) {
//每次循环出列一个对象 一直到队列为空
Tree tree= queue.poll();
List<Tree> children = parentMap.get(tree.getId());
if (CollectionUtils.isNotEmpty(children)) {
tree.setChild(children);
//如果有children集合 将children继续入列
children.forEach(queue::offer);
}
}
}