問題
我們經常需要遍歷這樣一種菜單結構:
對應的數據結構如下:
let list = [{ text: "A", children: [{text: "A1", children: null}, {text: "A2", children: null}] }, { text: "B", children: [ { text: "B1", children: [ {text: "B11", children: [{ text: "B111", children: null, }, { text: "B1112", children: null, }]}, {text: "B12", children: null}] }, { text: "B2", children: [{text: "B21", children: null}, {text: "B22", children: null}] }, ] }, { text: "C", children: null, }, { text: "D", children: [{text: "D1", children: null}, {text: "D2", children: null}] }];
這里給出幾種實現代碼:
實現
1.遞歸DFS
1 /* dfs recursive */ 2 function dfsRecursion(list) { 3 let result = []; 4 for(let i=0; i<list.length; ++i) { 5 result.push(list[i].text); 6 if(list[i].children) { 7 result.push(...dfs(list[i].children)); 8 } 9 } 10 return result; 11 }
2.迭代DFS
這里是使用棧來實現的,這里有個問題,這樣會修改原來的list,如果是JSON安全的話,
可以先存一份副本:JSON.parse(JSON.stringify(list));然后再進行相應的處理
/* dfs iteration 注意這種方式會修改原數組 */ function dfsIteration (list) { let result = []; for(let i=0; i<list.length; ++i) { result.push(list[i].text); if(list[i].children) { list.splice(i+1, 0, ...list[i].children); } } return result; }
或者這樣來實現
/* dfs iteration with stack */ function dfsIterationWithStack (list) { let result = []; stack = []; for(let i=0; i<list.length; ++i) { result.push(list[i].text); if(!list[i].children) { continue; } else { stack.push(...list[i].children.reverse()); } let popItem; while(stack.length != 0) { popItem = stack.pop(); result.push(popItem.text); popItem.children && stack.push(...popItem.children.reverse()); } } return result; }
3.遞歸BFS
/* bfs recursive */ function bfsRecursion(list) { let result = []; let children = []; for(let i=0; i<list.length; ++i) { result.push(list[i].text); if(list[i].children) { children.push(...list[i].children); } } if(children.length != 0) { return [...result, ...bfs(children)] } else { return result; } }
4.迭代BFS
使用數組收集每一層的元素,直到為空,也可稱之為層序遍歷。
/* bfs iteration 使用隊列來實現BFS */ function bfsIteration (list) { let result = [], children = []; while(list.length != 0) { for(let i=0; i<list.length; ++i) { result.push(list[i].text); if(list[i].children) { children.push(...list[i].children); } } list = children; children = []; } return result; }
完