JS廣度優先遍歷


自己用JS實現了 廣度優先遍歷

 第一種用了數組的高階函數,看起來有些復雜。然后思索着從可讀性上優化了一下,孰優孰劣以后分析。

var list = [{
    id: "ab", children: [{ id: "ab1", children: [{ id: "ab11", children: [] }] },{ id: "ab2", children: [] }, { id: "cd", children: [{ id: "aa", children: [] }, { id: "ef", children: [] }] }] },{ id:'cc', children:[] },{ id:'dd', children:[] }]
// path[] 1.將list 數組合並到path, 2.從頭部開始刪除,看是否有子節點,有就合並到path[] 3.重復2,直到path 為空

function breadthFirstSearch(list)
{
    let tree=[]; let path = list.reduce((acc,cur)=>acc=[].concat(acc,cur)); while(path.length>0){ let node = path.shift(); tree.push(node.id); let target = node.children; // console.log(target.length,node.id,target) if(target.length !== 0){ path=[].concat(path, ...target.length==1?target:target.reduce((acc,cur)=>acc=[].concat(acc,cur))); } } return tree; }
console.log(breadthFirstSearch(list))
// [
//     'ab',   'cc',
//     'dd',   'ab1',
//     'ab2',  'cd',
//     'ab11', 'aa',
//     'ef'
//   ]
// 非遞歸: 1.創建新的數組nodeList, 並賦值list 2.從頭遍歷nodeList的子節點,並合並到nodeList
function breadthFirstSearch1(list){
    let index=0; let tree=[]; let nodeList = [...list]; while(index<nodeList.length){ const node=nodeList[index++]; tree.push(node.id); if(node.children){ for(let k in node.children){ nodeList.push(node.children[k]); } } } return tree; // return nodeList; } console.log(breadthFirstSearch1(list))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM