BFE.dev is like a LeetCode for Front End developers. I’m using it to practice my skills.
This article is about the coding problem BFE.dev#104. Traverse DOM level by level
Analysis
Level by level, so initial level would be
[div]
then the next level is
[p, p, div]
then the next level is
[button, a, p, div]
We could just keeping pulling the elements from left, and push their children in from right, right ? This is a queue.
Show me the code
The implementation is BFS, not difficult, and we are only required to collect the elements, so doesn't need to care about the boundary of each level.
/**
* @param { HTMLElement } root
* @returns { HTMLElement[] }
*/
function flatten(root) {
if (root === null) return []
const queue = [root]
const result = []
while (queue.length > 0) {
const head = queue.shift()
result.push(head)
queue.push(...head.children)
}
return result
}
Passed
This is a fairly simple problem.
Hope it helps, you can have a try at here
Top comments (0)