JavaScript遍历树结构

遍历

function parseTreeJson(treeNodes){
    if(!treeNodes||!treeNodes.length)return;
    for(let i=0;i<treeNodes.length;i++){
        let childs=treeNodes[i].children;
        console.log(treeNodes[i].key)
        if(childs&&childs.length>0){
            parseTreeJson(childs);
        }
    }
}

广度非递归遍历

const travelWidely=(roots)=>{
    const queue = [...roots];
    while (queue.length){
        const node = queue.shift();
        //打印被遍历的节点
        if(node===undefined) return;
        console.log(`${node.title} ${node.children && node.children.length || ""}`);

        if(node.children&&node.children.length){
            queue.push(...node.children)
        }
    }
}
posted @ 2018-04-03 20:51  从过去穿越到现在  阅读(1001)  评论(0编辑  收藏  举报