当前位置:网站首页>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
边栏推荐
- Volcanic stone investment Zhang Suyang: hard technology, the relatively certain answer in the next 10 years
- 【安全】 阅读 RFC6749 及理解 Oauth2.0 下的授权码模式
- R语言使用lm函数构建线性回归模型、使用subset函数指定对于数据集的子集构建回归模型(使用floor函数和length函数选择数据前部分构建回归模型)
- 【C语言】结构体指针与结构体变量作形参的区别
- 要想组建敏捷团队,这些方法不可少
- Better and more modern terminal tools than xshell!
- Lyscript get previous and next instructions
- 严格模式——let和const——箭头函数——解构赋值——字符串模板symbol——Set和Map——生成器函数
- 最强分布式锁工具:Redisson
- word打字时后面的字会消失是什么原因?如何解决?
猜你喜欢

用非递归的方法实现二叉树中的层遍历,先序遍历,中序遍历和后序遍历

【安全】 阅读 RFC6749 及理解 Oauth2.0 下的授权码模式

【ECMAScript6】Promise

我秃了!唯一索引、普通索引我该选谁?

Denial of service DDoS Attacks

Operator3-设计一个operator

org.apache.ibatis.exceptions.TooManyResultsException的异常排查过程

Org.apache.ibatis.exceptions.toomanyresultsexception

面经整理,助力秋招,祝你称为offer收割机

Three men "running away" from high positions in the mobile phone factory
随机推荐
接口调不通,如何去排查?没想到10年测试老鸟栽在这道面试题上
What is the reason why the words behind word disappear when typing? How to solve it?
Tutorial on the principle and application of database system (061) -- MySQL exercise: operation questions 21-31 (V)
Poj3275 ranking the cows
vite在项目中配置路径别名
记一次使用pdfbox解析pdf,获取pdf的关键数据的工具使用
R语言可视化散点图、使用ggrepel包的geom_text_repel函数避免数据点之间的标签互相重叠(使用参数xlim和ylim将标签添加到可视化图像的特定区域、指定标签线段并添加箭头)
[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
【架构】评分较高的三本微服务书籍的阅读笔记
Paddleclas classification practice record
Tutorial on the principle and application of database system (059) -- MySQL exercise questions: operation questions 1-10 (III)
Use non recursive method to realize layer traversal, preorder traversal, middle order traversal and post order traversal in binary tree
C语言:归并排序
酷炫操作预热!代码实现小星球特效
Deploy application delivery services in kubernetes (Part 1)
最强分布式锁工具:Redisson
产品经理:岗位职责表
C language: quick sorting of sequential storage structure
UVA11175有向图D和E From D to E and Back题解
JWT login authentication + token automatic renewal scheme, well written!