樹形結(jié)構(gòu)跟數(shù)組遞歸互轉(zhuǎn)

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}

];

/**

* 數(shù)組轉(zhuǎn)樹? 非遞歸求解

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

* @param {Object} list

*/

function totree(list,parId) {

? ? let obj = {};

? ? let result = [];

? ? //將數(shù)組中數(shù)據(jù)轉(zhuǎn)為鍵值對結(jié)構(gòu) (這里的數(shù)組和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)

/**

* 數(shù)組轉(zhuǎn)樹? 遞歸求解

*/

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)

/**

* 樹轉(zhuǎn)數(shù)組扁平化結(jié)構(gòu)?

* 深度優(yōu)先遍歷? 堆棧? 后進先出

*/

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))

/**

* 樹轉(zhuǎn)數(shù)組扁平化結(jié)構(gòu)?

* 深度優(yōu)先遍歷? 遞歸

*/

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))

/**

* 廣度優(yōu)先

* 隊列? 先進先出

*/

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))

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

版權(quán)聲明:本文為CSDN博主「燦爾哈擦蘇」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容