当前位置:网站首页>leetcode-深度优先与广度优先遍历
leetcode-深度优先与广度优先遍历
2022-07-28 12:48:00 【Maic】
深度优先遍历与广度优先遍历,不刷算法题不知道这两个概念,平时业务也有些过这种场景,但是一遇到这两词就感觉高大上了
什么是深度优先遍历
深度优先遍历就是当我们搜索一个树的分支时,遇到一个节点,我们会优先遍历它的子节点直到最后根节点为止,最后再遍历兄弟节点,从兄弟子节点寻找它的子节点,直到搜索到最后结果,然后结束。
首先我们从上面一段话中,我们知道遍历的对象是树,树是一种数据结构,我们在js中可以模拟它,具体我们画一个图
以上就是一个基本的树结构,在js中我们可以用以下结构去描述
const root = {
name: '1',
children: [
{
name: '2-1',
children: [
{
name: '3-1',
children: [
{
name: '4-2',
children: null
},
{
name: '4-1',
children: null
}
]
},
{
name: '3-2',
children: null
}
]
},
{
name: '2-2',
children: null
}
]
}
我们理解上面那句话,深度优先遍历,就是当我搜索一个树分支,遇到一个节点,我就搜索她的子节点,直到搜索完了,再去搜索兄弟节点,我们用代码来验证一下
// 深度优先遍历
const deepDFS = (root, nodeList = []) => {
if (root) {
nodeList.push(root.name);
// 递归root.children,找root的子节点
root.children && root.children.forEach(v => deepDFS(v, nodeList))
}
return nodeList;
}
const result = deepDFS(root, []);
console.log(JSON.stringify(deepDFS(root, []), null, 2)))
/**
[
"1",
"2-1",
"3-1",
"4-2",
"4-1",
"3-2",
"2-2"
]
*/
从结果上来看发现从最开始的分支,从第一个分支开始,找到一个节点就一直找到最深的那个节点为止,然后再找父级兄弟节点,最后再从根子节点的兄弟节点去寻找子节点。
广度优先遍历
搜索树分支时,从根节点开始,当访问子节点时,先遍历找到兄弟节点,再寻找对应自己的子节点
我们用一个图来还原一下搜索过程
对应的代码如下
// 广度优先遍历
const deepBFS = (root, nodeList = []) => {
const queue = [root];
// 循环判断队列的长度是否大于0
while(queue.length > 0) {
// 取出队列添加的节点
const p = queue.shift();
nodeList.push(p.name);
// 根据节点是否含有children,如果有子节点则添加到队列中
p.children && p.children.forEach(v => queue.push(v))
}
return nodeList;
}
console.time('BFS-start')
const result = deepBFS(root, []);
console.log(JSON.stringify(result, null, 2));
console.timeEnd('BFS-start')
/*
[
"1",
"2-1",
"2-2",
"3-1",
"3-2",
"4-2",
"4-1"
]
*/
广度优先遍历的主要思想是将一个树放到一个队列中,我们循环这个队列,判断该队列的长度是否大于0,我们不断循环队列,shift出队列操作,然后判断节点children,循环children,然后将子节点添加到队列中,一旦队列的长度为0,那么就终止循环了。
我们测试一下两者哪种搜索时间效率更高
// BFS 广度优先遍历
console.time('BFS-start')
const result = deepBFS(root, []);
console.log(JSON.stringify(result, null, 2));
console.timeEnd('BFS-start');
// DFS 深度优先遍历
console.time('DFS-start');
console.log(JSON.stringify(deepDFS(root, []), null, 2));
console.timeEnd('DFS-start')
最后发现
广度优先遍历的时间明显比深度优先的时间效率要高,广度优先遍历是用队列记录了每一个节点的位置,所以会占用内存更多点,由于深度优先遍历是从根节点往子节点依次递归查询,当子节点查询完了,就从根的节点的兄弟节点依次往下搜索,所以比较耗时,搜索效率上广度优先遍历更高。
总结
1、理解深度优先遍历与广度优先遍历是什么
深度优先遍历就是从上到下,当我们搜索一个树时,我们从根开始,遇到一个节点,就先查询的它的子节点,如果子节点还有子节点就继续往下寻找直到最后没有为止,再从根子节点的兄弟节点开始依次向下寻找节点。而广度优先遍历遍历就是从根节点开始,寻找子节点,先遍历寻找兄弟节点,依次从上往下,按层级依次搜索。
2、用具体代码实现深度优先遍历与广度优先遍历
3、深度优先遍历比广度优先遍历更耗时
4、本文示例代码 code example[1]
参考资料
[1]code example: https://github.com/maicFir/lessonNote/blob/master/leetcode/leetcode-deepBFS.js
边栏推荐
- Blue Bridge Training (additional interview questions) day 7
- 面经整理,助力秋招,祝你称为offer收割机
- C语言:优化后的归并排序
- 【C语言】结构体指针与结构体变量作形参的区别
- R语言检验样本比例:使用prop.test函数执行单样本比例检验计算总体中成功样本比例p值的置信区间(设置conf.level参数指定置信水平、置信区间的大小)
- UVA11175有向图D和E From D to E and Back题解
- paddleClas分类实践记录
- Deployment之滚动更新策略。
- 【架构】评分较高的三本微服务书籍的阅读笔记
- Denial of service DDoS Attacks
猜你喜欢

蓝桥集训(附加面试题)第七天

Countdown 2 days! 2022 China Computing Conference: Mobile cloud invites you to meet with computing network for innovative development

Beyond istio OSS -- current situation and future of istio Service Grid

在 Kubernetes 中部署应用交付服务(第 1 部分)
![[dark horse morning post] byte valuation has shrunk to $270billion;](/img/58/8d5c78d919ed60bc833ec4daa22e23.jpg)
[dark horse morning post] byte valuation has shrunk to $270billion; "Second uncle" video author responded to plagiarism; Renzeping said that the abolition of the pre-sale system of commercial housing

最强分布式锁工具:Redisson

7.依赖注入

Some thoughts on.Net desktop development

SQL每日一练(牛客新题库)——第4天:高级操作符

org.apache.ibatis.exceptions.TooManyResultsException的异常排查过程
随机推荐
JWT login authentication + token automatic renewal scheme, well written!
[ecmascript6] function and its related use
Jar package
Half wave rectification light LED
R language test sample proportion: use prop The test function performs the single sample proportion test to calculate the confidence interval of the p value of the successful sample proportion in the
Realize the mutual value transfer between main window and sub window in WPF
DOJNOIP201708奶酪题解
[dark horse morning post] byte valuation has shrunk to $270billion; "Second uncle" video author responded to plagiarism; Renzeping said that the abolition of the pre-sale system of commercial housing
R语言检验样本比例:使用prop.test函数执行单样本比例检验计算总体中成功样本比例p值的置信区间(设置conf.level参数指定置信水平、置信区间的大小)
DXF读写:标注样式组码中文说明
国产API管理工具Eolink太好用了,打造高效的研发利器
数据库系统原理与应用教程(058)—— MySQL 练习题(二):单选题
Rust from introduction to mastery 01 introduction
R语言使用dpois函数生成泊松分布密度数据、使用plot函数可视化泊松分布密度数据(Poisson distribution)
R language ggplot2 visualization: use ggviolin function of ggpubr package to visualize violin diagram and set draw_ The quantiles parameter adds a specified quantile horizontal line (for example, 50%
[security] read rfc6749 and understand the authorization code mode under oauth2.0
I miss the year of "losing" Li Ziqi
C language: quick sorting of sequential storage structure
C language: merge sort
严格模式——let和const——箭头函数——解构赋值——字符串模板symbol——Set和Map——生成器函数