樹形結構跟數組遞歸互轉

let arr =[

? ? {id:2,name:'部門B',parentId:0},

? ? {id:3,name:'部門C',parentId:1},

? ? {id:1,name:'部門A',parentId:2},

? ? {id:4,name:'部門D',parentId:1}

];

/**

* 數組轉樹? 非遞歸求解

* 利用數組和對象相互引用? 時間復雜度O(n)

* @param {Object} list

*/

function totree(list,parId) {

? ? let obj = {};

? ? let result = [];

? ? //將數組中數據轉為鍵值對結構 (這里的數組和obj會相互引用)

? ? list.map(el => {

? ? ? ? obj[el.id] = el;

? ? })

? ? for(let i=0, len = list.length; i < len; i++) {

? ? ? ? let id = list[i].parentId;

? ? ? ? if(id == parId) {

? ? ? ? ? ? result.push(list[i]);

? ? ? ? ? ? continue;

? ? ? ? }

? ? ? ? if(obj[id].children) {

? ? ? ? ? ? obj[id].children.push(list[i]);

? ? ? ? } else {

? ? ? ? ? ? obj[id].children = [list[i]];

? ? ? ? }

? ? }

? ? return result;

}

let res1 = totree(arr,0)

/**

* 數組轉樹? 遞歸求解

*/

function toTree(list,parId){

let len = list.length

function loop(parId){

let res = [];

for(let i = 0; i < len; i++){

let item = list[i]

if(item.parentId === parId){

item.children = loop(item.id)

res.push(item)

}

}

return res

}

return loop(parId)

}

let result = toTree(arr,0)

/**

* 樹轉數組扁平化結構?

* 深度優先遍歷? 堆棧? 后進先出

*/

function deep(node){

let stack = node,

data = [];

while(stack.length != 0){

let pop = stack.pop();

data.push({

id: pop.id,

name: pop.name,

parentId: pop.parentId

})

let children = pop.children

if(children){

for(let i = children.length-1; i >=0; i--){

stack.push(children[i])

}

}

}

return data

}

//console.log(deep(res1))

/**

* 樹轉數組扁平化結構?

* 深度優先遍歷? 遞歸

*/

function deepTraversal(data) {

? ? const result = [];

? ? data.forEach(item => {

? ? ? ? const loop = data => {

? ? ? ? ? ? result.push({

? ? ? ? ? ? id: data.id,

name: data.name,

parentId: data.parentId

? ? ? ? ? ? });

? ? ? ? ? ? let child = data.children

? ? ? ? ? ? if(child){

? ? ? ? ? ? for(let i = 0; i < child.length; i++){

loop(child[i])

}

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? loop(item);

? ? })

? ? return result;

}

//console.log(deepTraversal(res1))

/**

* 廣度優先

* 隊列? 先進先出

*/

function wideTraversal(node){

let stack = node,

data = [];

while(stack.length != 0){

let shift = stack.shift();

data.push({

id: shift.id,

name: shift.name,

parentId: shift.parentId

})

let children = shift.children

if(children){

for(let i = 0; i < children.length; i++){

stack.push(children[i])

}

}

}

return data

}

//console.log(wideTraversal(res1))

————————————————

版權聲明:本文為CSDN博主「燦爾哈擦蘇」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。

原文鏈接:https://blog.csdn.net/susuzhe123/java/article/details/95353403

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。