
什么是深度优先遍历
深度优先遍历:尽可能深的搜索树的分支
深度优先遍历算法口诀
访问根节点;
对根节点的children挨个进行深度优先遍历。
const tree = {
val: 'a',
children: [
{
val: 'b',
children: [
{
val: 'd',
children: []
},
{
val: 'e',
children: []
}
]
},
{
val: 'c',
children: [
{
val: 'f',
children: []
},
{
val: 'g',
children: []
}
]
}
]
}
const dfs = (root) => {
console.log(root.val);
// root.children.forEach((child) => {dfs(child)});
root.children.forEach(dfs);
}
dfs(tree);
运行结果:
a b d e c f g
本文深入解析深度优先遍历算法,通过实例演示如何在JavaScript中使用递归实现树形数据结构的遍历,最终输出'abdecfg'。适合理解递归和数据结构初学者。
980

被折叠的 条评论
为什么被折叠?



