1. 遍历树
(1)广度遍历
/**
*
* @param {*} node 根结点
* @param {*} fn 对遍历结点做的操作
* @returns
*/
var treeFind = function (node, fn) {
if (!node) return
var arr = [node]
while(arr && arr.length) {
const current = arr.shift()
fn(current)
if (current.children) {
arr.push(...node.children)
}
}
}
(2)深度遍历
深度遍历有两种方式,一种是递归,一种是栈
递归方式,如下:
/**
*
* @param {*} tree 结点,如果传入的不是数据,需要放入数组中
* @param {*} fn 对遍历结点做的操作
* @returns
*/
var treeFind = function (tree, fn) {
let nodes = tree
if (!Array.isArray(tree)) {
nodes = [tree]
}
if (!nodes || !nodes.length) return
for (let i = 0; i < nodes.length; i++) {
fn(nodes[i])
treeFind(nodes[i].children, fn)
}
}
栈的方式如下:
/**
*
* @param {*} node 根结点
* @param {*} fn 对遍历结点做的操作
* @returns
*/
var treeFind = function (node, fn) {
if (!node) return
var arr = [node]
while(arr && arr.length) {
const current = arr.pop()
fn(current)
if (current.children) {
arr.push(...current.children)
}
}
}