---
description: 考你 DOM 跟 while, queue 應用
---

# DOM tree with 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&#x26;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;
}
```
