一、写在前面
本篇博客主要是对树的一些遍历方式进行总结,其中包含树的深度优先遍历
,和树的广度优先遍历
,以及二叉树的先中后序遍历
,其中先中后序遍历
分别使用递归版本
的遍历方式和非递归版本
的递归方式。
二、树的深度优先遍历和广度优先遍历
如上图所示为我们需要遍历的数结构。
数据可以整理为:
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(item => {
dfs(item)
})