深度优先和广度优先

文章目录


前言

深度优先和广度优先的区别:

  1. 搜索方式不同 。深度优先搜索算法不全部保留结点,扩展完的结点从数据库中弹出删去;广度优先搜索算法需存储产生的所有结点。
  2. 运行速度不同 。深度优先搜索算法有回溯操作,运行速度慢;广度优先搜索算法无回溯操作,运行速度快。
  3. 占用空间不同 。深度优先搜索算法占用空间少;广度优先搜索算法占用空间大。
  4. 作用不同。虽然都可以完成树形结构的遍历,但是深度优先一般用于需要先处理最深层级逻辑,广度优先一般用于层层节点展开的处理逻辑;

一、深度和广度的区别

  • 深度优先: 1>3>7>6>2>5>4
  • 广度优先: 1>2>3>4>5>6>7

二、代码演示

1.准备数据,构造树

代码如下(示例):

java 复制代码
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;
    }

}

2.深度优先遍历

代码如下(示例):

java 复制代码
    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"

3.广度优先遍历

代码如下(示例):

java 复制代码
    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"


总结

深度优先 用栈;广度优先 用队列;

相关推荐
8Qi82 分钟前
LeetCode 32:最长有效括号 —— 栈 + 标记法 题解
java·数据结构·算法·leetcode·职场和发展··括号匹配
机器学习之心4 分钟前
198种组合算法+优化CNN-LSTM+SHAP分析+新数据预测+多输出!深度学习可解释分析,强烈安利,粉丝必备
深度学习·算法·cnn-lstm·shap分析·198种组合算法
Tairitsu_H4 分钟前
[LC优选算法#3] 滑动窗口 | 将x减到0的最⼩操作数 | ⽔果成篮 | 字⺟异位词
c++·算法·leetcode·滑动窗口
bIo7lyA8v11 分钟前
算法复杂度与能耗关系的多变量分析研究的技术8
算法
洛水水40 分钟前
【力扣100题】76.搜索插入位置
数据结构·算法·leetcode
Techblog of HaoWANG44 分钟前
智巡守卫:多模态巡检智能体算法服务端设计与实现——基于Ollama+Qwen3.5的自动化巡检报告生成系统
运维·人工智能·算法·目标检测·自动化·边缘计算
小蒋学算法1 小时前
算法-灌溉花园的最少龙头数目-贪心
算法
满怀冰雪1 小时前
第07篇-差分算法-高效处理区间修改问题
数据结构·算法
KaMeidebaby1 小时前
卡梅德生物技术快报|重组蛋白的表达和纯化:工艺调试全记录:大肠杆菌体系重组蛋白的表达和纯化参数标定(肠激酶轻链案例)
前端·人工智能·算法·数据挖掘·数据分析
ZPC82101 小时前
如何将机械臂末端定位精度提升至微米如何进行标定
人工智能·算法·机器人