学习DOM-DIFF与Fiber时,常常听到深度优先与广度优先
这两个名词,本文做下代码实现与总结
//示例
const root = {
name: 'A1',
children: [
{
name: 'B',
children: [
{
name: 'B1'
},
{
name: 'B2'
}
]
},
{
name: 'C',
children: [
{
name: 'C1'
},
{
name: 'C2'
}
]
}
]
}
//深度优先
function dfs(node) {
console.log(node.name);
node.children?.forEach(dfs);
}
dfs(root) // A B B1 B2 C C1 C2
//广度优先
function bfs(node) {
const stack = [];
stack.push(node);
let current;
while((current = stack.shift())) {
console.log(current.name);
current.children?.forEach(child => {
stack.push(child);
})
}
}
bfs(root) // A B C B1 B2 C1 C2