跳至主要內容

基础的js树的遍历

YueHui...小于 1 分钟javascriptjavascript

基础的js树的遍历

可直接复制代码到浏览器查看效果

const dataList = [
    {
        name:"a",
        children:[
            {
                name:"a-1",
                children:[
                    { name:"a-1-1" },
                    { name:"a-1-2" },
                ]
            },
            {
                name:"a-2",
                children:[
                    {name:"a-2-1"},
                    {name:"a-2-2"}
                ]
            }
        ]
    },{
        name:"b",
        children:[
            {
                name:"b-1",
                children:[
                    { name:"b-1-1" },
                    { name:"b-1-2" },
                ]
            },
            {
                name:"b-2",
                children:[
                    {name:"b-2-1"},
                    {name:"b-2-2"}
                ]
            }
        ]
    }
];

/**
 *深度优先递归
 */
(function deepFirst(list){
    list.forEach(item=>{
        console.log(item.name);
        if(item.children) deepFirst(item.children)
    })
})(dataList);

/**
 * 深度优先非递归
 */
(function(list){
    let queue = list;
    while (queue.length >0){
        const item = list.shift();
        console.log(item.name);
        if(item.children){
            item.children.reverse();
            item.children.forEach(child=>{
                queue.unshift(child);
            })
        }

    }
})(JSON.parse(JSON.stringify(dataList)));

/**
 * 广度优先递归
 */
(function wideFirst(list){
    let children = [];
    list.forEach(item=>{
        console.log(item.name);
        if(item.children){
            children = children.concat(item.children);
        }
    })
    if(children.length>0) wideFirst(children);
})(dataList);

/**
 * 广度优先非递归
 */
(function(list){
    const queue = list;
    while (queue.length){
        const item = queue.shift();
        console.log(item.name);
        if(item.children){
            item.children.forEach(child=>{
                queue.push(child)
            })
        }
    }
})(JSON.parse(JSON.stringify(dataList)));

上次编辑于:
贡献者: YueHui