深度优先和广度优先

文章目录


前言

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

  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"]


总结

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

相关推荐
tainshuai1 小时前
用 KNN 算法解锁分类的奥秘:从电影类型到鸢尾花开
算法·分类·数据挖掘
Coovally AI模型快速验证7 小时前
农田扫描提速37%!基于检测置信度的无人机“智能抽查”路径规划,Coovally一键加速模型落地
深度学习·算法·yolo·计算机视觉·transformer·无人机
pusue_the_sun7 小时前
数据结构:二叉树oj练习
c语言·数据结构·算法·二叉树
RaymondZhao348 小时前
【全面推导】策略梯度算法:公式、偏差方差与进化
人工智能·深度学习·算法·机器学习·chatgpt
zhangfeng11338 小时前
DBSCAN算法详解和参数优化,基于密度的空间聚类算法,特别擅长处理不规则形状的聚类和噪声数据
算法·机器学习·聚类
啊阿狸不会拉杆9 小时前
《算法导论》第 32 章 - 字符串匹配
开发语言·c++·算法
小学生的信奥之路9 小时前
洛谷P3817题解:贪心算法解决糖果分配问题
c++·算法·贪心算法
你知道网上冲浪吗10 小时前
【原创理论】Stochastic Coupled Dyadic System (SCDS):一个用于两性关系动力学建模的随机耦合系统框架
python·算法·数学建模·数值分析
地平线开发者11 小时前
征程 6 | PTQ 精度调优辅助代码,总有你用得上的
算法·自动驾驶
Tisfy12 小时前
LeetCode 837.新 21 点:动态规划+滑动窗口
数学·算法·leetcode·动态规划·dp·滑动窗口·概率