No.104 question of BFE.dev, link here traverse DOM level by level.
This question is asking us to traverse dom level by level, so it’s a BFS obviously, to achieve a BFS, we need to use queue this data structure.
Before we start, it’s necessary to take a check of edge case, so if root is ull return an empty array.
Then, we initialize a queue which equals to [root], so at this time, there is the root node of DOM in this queue, and we also need a result to load each element of DOM, then we can use a while loop to iterate through the queue and shift an element of it then push the shifted element into the result. After this, our queue is empty, so we need to push left DOM into our queue, and DOM nodes have their children nodes, so we can simply push their children and use a spread operator.
After that, our work is done, and we can return our result.
function flatten(root) {
if (!root) return []
const queue = [root]
const result = []
while(queue.length) {
const node = queue.shift()
result.push(node)
queue.push(...node.children)
}
return result
}
这篇文章讨论了如何使用宽度优先搜索(BFS)方法在JavaScript中遍历DOM树,通过队列数据结构逐层处理节点。作者提供了`flatten`函数的代码示例,包括处理边界情况和处理子节点的过程。

被折叠的 条评论
为什么被折叠?



