当前位置:网站首页>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
边栏推荐
- Jar package
- 30 day question brushing training (I)
- Poj3275 ranking the cows
- UVA11175有向图D和E From D to E and Back题解
- Merge table rows - three levels of for loop traversal data
- Debezium系列之:2.0.0.Beta1的重大变化和新特性
- C language: random generated number + merge sort
- 解决跨越的几种方案
- JWT login authentication + token automatic renewal scheme, well written!
- R语言使用lm函数构建线性回归模型、使用subset函数指定对于数据集的子集构建回归模型(使用floor函数和length函数选择数据前部分构建回归模型)
猜你喜欢

30天刷题计划(四)

Customized template in wechat applet

最强分布式锁工具:Redisson

Today's sleep quality record 75 points

Three men "running away" from high positions in the mobile phone factory

Humiliation, resistance, reversal, 30 years, China should win Microsoft once

Denial of service DDoS Attacks

Use non recursive method to realize layer traversal, preorder traversal, middle order traversal and post order traversal in binary tree

Half wave rectification light LED

Strict mode -- let and const -- arrow function -- Deconstruction assignment -- string template symbol -- set and map -- generator function
随机推荐
使用 IPtables 进行 DDoS 保护
C语言:随机生成数+归并排序
Lyscript get previous and next instructions
C language: quick sorting of sequential storage structure
图的遍历(BFS&&DFS基础)
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
Deployment之滚动更新策略。
What if the server cannot be connected (the original server cannot find the target resource)
R language ggplot2 visualization: use the ggviolin function of ggpubr package to visualize violin diagrams, set the palette parameter, and customize the border colors of violin diagrams at different l
R language uses LM function to build multiple linear regression model, writes regression equation according to model coefficient, and uses conflict function to give 95% confidence interval of regressi
UVA1599理想路径题解
Analyzing the principle of DNS resolution in kubernetes cluster
.net for subtraction, intersection and union of complex type sets
R语言使用dpois函数生成泊松分布密度数据、使用plot函数可视化泊松分布密度数据(Poisson distribution)
Using fail2ban to protect web servers from DDoS Attacks
SQL daily practice (Niuke new question bank) - day 4: advanced operators
力扣 2354. 优质数对的数目
30 day question brushing training (I)
Rust 从入门到精通01-简介
在 Kubernetes 中部署应用交付服务(第 1 部分)