当前位置:网站首页>Leetcode depth first and breadth first traversal
Leetcode depth first and breadth first traversal
2022-07-28 13:51:00 【Maic】
Depth-first traversalAndBreadth first traversal, Do not brush algorithm problems do not know these two concepts , There are also some such scenarios in business at ordinary times , But when I meet these two words, I feel tall
What is depth first traversal
Depth-first traversal When we search for a Trees When the branches of , Meet a node , We will first traverse its child nodes until the last root node , Finally, traverse the sibling nodes , Look for its child nodes from the sibling child nodes , Until the final result is found , Then the end .
First of all, from the above paragraph , We know that the traversal object is a tree , A tree is a data structure , We are js You can simulate it in , Let's draw a picture
The above is a basic tree structure , stay js We can use the following structure to describe
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
}
]
}
We understand the above sentence , Depth-first traversal , When I search for a branch of a tree , Encounter a node , I will search her child nodes , Until the search is over , Then go to search brother nodes , Let's use the code to verify
// Depth-first traversal
const deepDFS = (root, nodeList = []) => {
if (root) {
nodeList.push(root.name);
// recursive root.children, look for root Child nodes of
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"
]
*/
From the result, we found that the branch from the beginning , Start with the first branch , Find a node and keep finding the deepest node , Then find the parent sibling node , Finally, find the child nodes from the brother nodes of the root child nodes .
Breadth first traversal
When searching tree branches , Start at the root node , When accessing child nodes , First, traverse to find the sibling node , Then find the corresponding child node
Let's use a graph to restore the search process
The corresponding code is as follows
// Breadth first traversal
const deepBFS = (root, nodeList = []) => {
const queue = [root];
// Loop to determine whether the length of the queue is greater than 0
while(queue.length > 0) {
// Take out the node added by the queue
const p = queue.shift();
nodeList.push(p.name);
// Depending on whether the node contains children, If there are child nodes, they are added to the queue
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"
]
*/
Breadth first traversal The main idea is to put a tree in a queue , We cycle through the queue , Determine whether the length of the queue is greater than 0, We keep cycling the queue ,shift Out of queue operation , Then determine the node children, loop children, Then add the child nodes to the queue , Once the queue length is 0, Then the loop is terminated .
Let's test which is more efficient in search time
// BFS Breadth first traversal
console.time('BFS-start')
const result = deepBFS(root, []);
console.log(JSON.stringify(result, null, 2));
console.timeEnd('BFS-start');
// DFS Depth-first traversal
console.time('DFS-start');
console.log(JSON.stringify(deepDFS(root, []), null, 2));
console.timeEnd('DFS-start')
Finally found
The time efficiency of breadth first traversal is obviously higher than that of depth first traversal , Breadth first traversal records the position of each node in a queue , So it will occupy more memory , Because depth first traversal is a recursive query from the root node to the child nodes , When the child nodes are queried , Search from the sibling nodes of the root node , So it's time consuming , Breadth first traversal is more efficient .
summary
1、 understand Depth-first traversal And Breadth first traversal What is it?
Depth-first traversal From top to bottom , When we search a tree , We start from the root , Encounter a node , Just query its child nodes first , If the child node has child nodes, continue to search until there are no child nodes , Then start from the sibling nodes of the root child node and look for the nodes in turn . and Breadth first traversal Traversal starts from the root node , Look for child nodes , First traverse to find sibling nodes , From top to bottom , Search by level .
2、 With concrete code Depth-first traversal And Breadth first traversal
3、 Depth first traversal is more time-consuming than breadth first traversal
4、 Sample code of this article code example[1]
Reference material
[1]code example: https://github.com/maicFir/lessonNote/blob/master/leetcode/leetcode-deepBFS.js
边栏推荐
- 30天刷题计划(二)
- 我秃了!唯一索引、普通索引我该选谁?
- 使用 Fail2ban 保护 Web 服务器免受 DDoS 攻击
- 掌握闭包,夯实基本功
- 最强分布式锁工具:Redisson
- org.apache.ibatis.exceptions.TooManyResultsException的异常排查过程
- No swagger, what do I use?
- Blue Bridge Training (additional interview questions) day 7
- P1797 heavy transportation problem solution
- R语言ggplot2可视化:可视化散点图并为散点图中的数据点添加文本标签、使用ggrepel包的geom_text_repel函数避免数据点标签互相重叠(自定义指定字体类型font family)
猜你喜欢

How to check if the interface cannot be adjusted? I didn't expect that the old bird of the 10-year test was planted on this interview question

30天刷题计划(二)

最强分布式锁工具:Redisson

Some thoughts on.Net desktop development

SAP ui5 fileuploader control realizes local file upload, and trial version of cross domain access error encountered when receiving server-side response

30天刷题计划(四)

DXF读写:对齐尺寸标注文字居中、上方的位置计算

No swagger, what do I use?

30 day question brushing plan (II)

Socket类关于TCP字符流编程的理解学习
随机推荐
LyScript 获取上一条与下一条指令
UVA11175有向图D和E From D to E and Back题解
SQL daily practice (Niuke new question bank) - day 4: advanced operators
持续(集成-->交付-->部署)
基于神经网络的帧内预测和变换核选择
我秃了!唯一索引、普通索引我该选谁?
leetcode(442)数组中重复的数据
Org.apache.ibatis.exceptions.toomanyresultsexception
【C语言】结构体指针与结构体变量作形参的区别
DDoS protection with iptables
Can second uncle cure young people's spiritual internal friction?
Graph traversal (BFS & DFS basis)
产品经理:岗位职责表
C语言:顺序存储结构的快速排序
Excellent performance! Oxford, Shanghai, AI Lab, Hong Kong University, Shangtang, and Tsinghua have joined forces to propose a language aware visual transformer for reference image segmentation! Open
算法---不同路径(Kotlin)
Three men "running away" from high positions in the mobile phone factory
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%
【架构】评分较高的三本微服务书籍的阅读笔记
【安全】 阅读 RFC6749 及理解 Oauth2.0 下的授权码模式