深度遍历:
每次学习的时候,我都很想找一份树的数据,但是总是找不到。。这里直接贴,可以复制过去学习用~
// 数据
const tree = {
name: '1',
children: [
{
name: '1-1',
children: [
{
name: '1-1-1',
},
{
name: '1-1-2',
children: [
{
name: '1-1-2-1',
children: [
{
name: '1-1-2-1-1'
},
]
},
{
name: '1-1-2-2'
}
],
},
{
name: '1-1-3',
}
]
},
{
name: '1-2',
},
{
name: '1-3',
children: [
{
name: '1-3-1',
children: [
{
name: '1-3-1-1'
}
]
},
{
name: '1-3-2',
children: [
{
name: '1-3-2-1'
}
]
},
{
name: '1-3-3',
children: [
{
name: '1-3-3-1'
}
]
}
]
},
],
}
复制代码
深度遍历
const deep = data => {
// 最终的 name 序列
const res = []
// 递归函数
const traverse = obj => {
const { children, name } = obj
res.push(name)
// 直接 forEach 递归即可
if (children && children.length) {
children.forEach(child => {
traverse(child)
});
}
}
// 调用即可
traverse(data)
return res
}
复制代码
广度遍历
const BFS = data => {
// 栈stack: 先进先出
const stack = []
// 结果集
const res = []
// 把第一个元素丢进栈
stack.push(data)
while(stack.length) {
// 这里一定要用变量接收, 不然后面shift数组的长度就变了
const len = stack.length
// 每个while其实就是树的每一层
for (let i = 0; i < len; i++) {
// 这里是 shift 不是 pop 这和你最终结果的顺序有关
const item = stack.shift();
const { name, children } = item
res.push(name)
// 将每一层的每个数据再丢进栈中
if (children && children.length) {
stack.push(...children)
}
}
}
return res
}
复制代码
每天进步一点点~~~~~~
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END