深度优先和广度优先

文章目录


前言

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

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


总结

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

相关推荐
LYFlied17 分钟前
【每日算法】LeetCode 19. 删除链表的倒数第 N 个结点
算法·leetcode·链表
踏浪无痕20 分钟前
计算机算钱为什么会算错?怎么解决?
后端·算法·面试
夏乌_Wx31 分钟前
练题100天——DAY28:找消失的数字+分发饼干
数据结构·算法
studytosky1 小时前
深度学习理论与实战:反向传播、参数初始化与优化算法全解析
人工智能·python·深度学习·算法·分类·matplotlib
WolfGang0073211 小时前
代码随想录算法训练营Day48 | 108.冗余连接、109.冗余连接II
数据结构·c++·算法
努力学算法的蒟蒻2 小时前
day35(12.16)——leetcode面试经典150
算法·leetcode·面试
cccc来财2 小时前
角点检测算法:Harris 和 FAST 方法
算法·计算机视觉·特征提取
风中月隐2 小时前
C语言中以坐标的方式图解“字母金字塔”的绘制
c语言·开发语言·算法·字母金子塔·坐标图解法
q_30238195562 小时前
告别“笨重”检测!VA-YOLO算法让疲劳驾驶识别更轻更快更准
算法·yolo
松涛和鸣2 小时前
DAY32 Linux Thread Programming
linux·运维·数据库·算法·list