> For the complete documentation index, see [llms.txt](https://hannahpun.gitbook.io/leetcode-note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hannahpun.gitbook.io/leetcode-note/queue/dom-tree-with-queue.md).

# DOM tree with queue

考你 DOM 跟 while, queue 應用

[Traverse DOM level by level](https://bigfrontend.dev/problem/Traverse-DOM-level-by-level)

Given a DOM tree, flatten it into an one dimensional array, in the order of layer by layer, like below.

<figure><img src="https://1787585077-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LqirD3iAZIDk4oDCfwS%2Fuploads%2FUR3tdF1cA9UmjeI49mcR%2FykqFdOIOaXFyn2uZ8h5Lt02sFaYb5eZ8_1063x546_1598232821941.png?alt=media&amp;token=cebcad54-4233-4df4-bb28-0be5e840dc52" alt=""><figcaption></figcaption></figure>

```javascript
/**
 * @param {HTMLElement | null} root
 * @return {HTMLElement[]}
 */
function flatten(root) {
  const result = [];
  if (!root) {
    return result;
  }
  const queue = [root];
  while (queue.length) {
    const node = queue.shift();
    result.push(node);
    for (const child of node.children) {
      queue.push(child);
    }
  }
  return result;
}
```
