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ù)組和對象相互引用? 時(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)先遍歷? 堆棧? 后進(jìn)先出
*/
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)先
* 隊(duì)列? 先進(jìn)先出
*/
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