1.深度優先
2.廣度優先
兩者的區別
對於算法來說 無非就是時間換空間 空間換時間
- 深度優先不需要記住所有的節點, 所以占用空間小, 而廣度優先需要先記錄所有的節點占用空間大
- 深度優先有回溯的操作(沒有路走了需要回頭)所以相對而言時間會長一點
深度優先采用的是堆棧的形式, 即先進后出
廣度優先則采用的是隊列的形式, 即先進先出
具體代碼
const data = [
{
name:
'a'
,
children: [
{ name:
'b'
, children: [{ name:
'e'
}] },
{ name:
'c'
, children: [{ name:
'f'
}] },
{ name:
'd'
, children: [{ name:
'g'
}] },
],
},
{
name:
'a2'
,
children: [
{ name:
'b2'
, children: [{ name:
'e2'
}] },
{ name:
'c2'
, children: [{ name:
'f2'
}] },
{ name:
'd2'
, children: [{ name:
'g2'
}] },
],
}
]
// 深度遍歷, 使用遞歸
function
getName(data) {
const result = [];
data.forEach(item => {
const map = data => {
result.push(data.name);
data.children && data.children.forEach(child => map(child));
}
map(item);
})
return
result.join(
','
);
}
// 廣度遍歷, 創建一個執行隊列, 當隊列為空的時候則結束
function
getName2(data) {
let
result = [];
let
queue = data;
while
(queue.length > 0) {
[...queue].forEach(child => {
queue.shift();
result.push(child.name);
child.children && (queue.push(...child.children));
});
}
return
result.join(
','
);
}
console.log(getName(data))
console.log(getName2(data))