当前位置:网站首页>[JS] - [DFS, BFS application] - learning notes
[JS] - [DFS, BFS application] - learning notes
2022-06-28 07:53:00 【Interesting learning】
【js】-【DFS、BFS application 】- Learning notes
1 Traversal of binary tree - recursive -DFS
// The input parameters of all traversal functions are the root node objects of the tree
function preorder(root) {
// Recursive boundary ,root It's empty
if(!root) {
return
}
// Output the current traversal node value
console.log(' The node value currently traversed is :', root.val)
// Recursively traverses the left subtree
preorder(root.left)
// Recursively traverses the right subtree
preorder(root.right)
}
2 Sequence traversal of binary tree -BFS
function BFS(root) {
const queue = [] // Initialize queue queue
// The root node joins the team first
queue.push(root)
// The queue is not empty , Description not completely traversed
while(queue.length) {
const top = queue[0] // Take out the team leader element
// visit top
console.log(top.val)
// If the left subtree exists , Zuozhu joins the team
if(top.left) {
queue.push(top.left)
}
// If the right subtree exists , Right subtree joins the team
if(top.right) {
queue.push(top.right)
}
queue.shift() // Access to complete , Team leader element out of the team
}
}
BFS(root) // perform BFS
3 Given a sequence without repeating numbers , Return all possible permutations
https://mp.csdn.net/mp_blog/creation/success/124684440
Example :
Input : [1,2,3]
Output : [
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
// The input parameter is an array
const permute = function(nums) {
// The length of the cache array
const len = nums.length
// curr Variable is used to record the current arrangement
const curr = []
// res Used to record all the permutations
const res = []
// visited To avoid repeating the same number
const visited = {
}
// Definition dfs function , The input parameter is the index of the pit ( from 0 Count )
function dfs(nth) {
# If you traverse to a nonexistent pit ( The first len+1 individual ), Touch the recursive boundary to return
if(nth === len) {
// Before this time len Pits have been filled , Record the corresponding arrangement
res.push(curr.slice())
return
}
// Check what numbers are left in your hand
for(let i=0;i<len;i++) {
// if nums[i] It has not been used by other pits before , It can be understood as “ This number is left ”
if(!visited[nums[i]]) {
# to nums[i] To make a “ Used ” Mark of
visited[nums[i]] = 1
// take nums[i] Push current arrangement
curr.push(nums[i])
// Based on this arrangement, continue to the next pit
dfs(nth+1)
// nums[i] Get out of the current pit
curr.pop()
// Fall down “ Used ” identification
visited[nums[i]] = 0
}
}
}
# From index to 0 Pit position ( That is, the first pit ) Start dfs
dfs(0)
return res
};
res.push(curr.slice()) Not simply res.push(curr) . Why do you do this ? Because there is only one unique curr , curr The value of dfs And constantly updated . slice The function of the method is to help us copy out one that does not affect curr A copy of the original , In case of direct modification to curr References to .
4 Given a set of integers without repeating elements nums, Returns all possible subsets of the array
https://mp.csdn.net/mp_blog/creation/success/124684440
Example : Input : nums = [1,2,3]
Output :
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
const combine = function(n, k) {
// Initializing the result array
const res = []
// Initialize the combined array
const subset = []
// Get into dfs, The starting number is 1
dfs(1)
// Definition dfs function , The input parameter is the number currently traversed
function dfs(index) {
if(subset.length === k) {
res.push(subset.slice())
return
}
// Start with the value of the current number , Traverse index-n All numbers between
for(let i=index;i<=n;i++) {
// This is the case when the current number exists in the combination
subset.push(i)
// Based on the fact that the current number exists in the combination , further dfs
dfs(i+1)
// This is the case when the current number does not exist and is being combined
subset.pop()
}
}
// Return result array
return res
};
function allSubsets(arr){
let res = [[]];
for(let i = 0; i < arr.length; i++){
const tempRes = res.map(subset => {
const one = subset.concat([]);
one.push(arr[i]);
return one;
})
res = res.concat(tempRes);
}
return res;
}
边栏推荐
- HJ prime factor
- Ambari (IX) --- use expect to realize no interaction in ambri server setup phase (valid for personal test)
- Unity UI shadow component
- kubernetes删除pod的流程的源码简析
- Analyze 5 indicators of NFT project
- flutter 实现摇一摇功能
- Hj21 simple password
- 剑指Offer||:链表(简单)
- DBeaver 22.1.1 发布,可视化数据库管理平台
- 大型项目中的Commit Message规范化控制实现
猜你喜欢

Kubernetes理论基础

分析 NFT 项目的 5 个指标

Section VI UART of zynq

SOC clock configuration

Open62541 import nodeset file directly

Kubernetes deploys a secret pit where thanos ruler sends repeated alarms
![[thanos source code analysis series]thanos query component source code analysis](/img/e4/2a87ef0d5cee0cc1c1e1b91b6fd4af.png)
[thanos source code analysis series]thanos query component source code analysis

Uninstall and reinstall the latest version of MySQL database. The test is valid

Host is not allowed to connect to this MySQL server

ZYNQ_ IIC read / write m24m01 record board status
随机推荐
Ambari (VII) --- ambari integrated hue4.2 document (valid for personal test)
Kubernetes cluster command line tool kubectl
NDK cross compilation
"Three routines" of digital collection market
Llvm and clang
HJ prime factor
Sword finger offer|: linked list (simple)
SOC clock configuration
GoLand IDE and delve debug Go programs in kubernetes cluster
HJ进制转换
Flutter realizes the function of "shake"
HJ字符串排序
推荐系统系列精讲(第五讲): 排序模型的调优实践
PLC -- Notes
HJ base conversion
券商注册开户靠谱吗?安全吗?
HJ质数因子
Study notes 22/1/17
ES6 use of return in arrow function
大型项目中的Commit Message规范化控制实现