1 树状结构

var result = {
    id:0,
    name:"张飞",
    item:[
        {id:1,name:"关羽"},
        {id:2,name:"刘备",item:[
            {id:5,name:"荀彧"},
            {id:6,name:"关平"}

        ]},
        //点击曹操这一项,加载出来刘禅和周仓,点击周仓,又异步加载项羽和别姬
        {id:3,name:"曹操",item:[
            {id:8,name:"刘禅"},
            {id:9,name:"周仓",item:[
                {id:10,name:"项羽"},
                {id:11,name:"别姬"}
            ]}
        ]},
        {id:4,name:"貂蝉"},
    ]
}
function cb(node) {
  console.log(node)
}

2 深度优先

function dfs(nodes,key,cb,parent=null,args=null){
    //对于入参的判断,node必须存在且是一个数组,如果不是,进行矫正
    //key 必须是一个字符串,不能是函数之类的
    // cb必须是一个函数
    if(!nodes){
        return false;
    }
    if(typeof cb != 'function') {
        return fasle;
    }
    if(!Array.isArray(nodes)) {
        nodes = [nodes];
    }
    nodes.forEach((node) => {
        cb(node,parent,args)
        dfs(node[key],key,cb,node,args)
    })
}

3 广度优先

function bfs(nodes,cb,childKey,parent = null) {
    if(!nodes){
        return false;
    }
    if(typeof cb != 'function') {
        return fasle;
    }
    if(!Array.isArray(nodes)) {
        nodes = [nodes];
    }
    const stack = [];
    nodes.forEach((node) => {
        stack.push(node);
    })
    while(stack.length > 0) {
        let node = stack.shift();
        cb(node);
        stack.push(...(node[childKey] || []));
    }
}

jimwmg
151 声望4 粉丝

点点滴滴,不忘初心