Skip to curriculum
Jump to the editor

21.2. Flatten tree records and keep each node

Medium
Topics
20–30 min

Trees arrive nested: a menu with submenus, a folder with folders, a comment with replies, each node holding a children array. Tables, search indexes and virtualized lists want the opposite: one flat list of rows, where each row still knows where it sat in the tree.

Write flattenTree(roots) in flatten-tree.js. It walks the tree depth first and returns one row per node. A row has the node's own fields without children, plus three fields that record the node's place: parentId, depth and path.

Signature

JAVASCRIPT
function flattenTree(roots) // returns an array of rows
  • roots: an array of root nodes, or a single root node. A node is an object with an id, any other fields, and optionally children, an array of nodes.
  • Returns a new array of new objects. Each row is the node's fields except children, then:
    • parentId: the id of the node's parent, or null for a root;
    • depth: 0 for a root, one more for each level down;
    • path: an array of ids from the root down to this node, the node's own id last.

Requirements

  1. A root becomes a row with parentId: null, depth: 0 and path: [id].
  2. A child's row has its parent's id, the parent's depth plus one, and the parent's path plus its own id.
  3. Rows are in depth-first order: a node, then all of its descendants, then its next sibling. Children keep their order.
  4. roots may be an array (several roots, or none) or one node object.
  5. Rows have no children field. Every other field is kept as it is, including 0, "", false and null; object fields are not copied deeply.
  6. Rows are new objects, and the tree is not changed.
  7. Each row has its own path array: changing one row's path never changes another's.
  8. An id of 0 is a real id: its children get parentId: 0.
  9. A missing, null or empty children means a leaf. null, undefined and holes inside a children array are skipped.
  10. A node that appears under two parents is listed under each, with that parent's parentId and path.
  11. A node that contains itself (directly or deeper) makes flattenTree throw a TypeError.
  12. parentId, depth and path always describe the tree, even if a node already has fields with those names.
  13. A chain 2,000 levels deep works.

Examples

JAVASCRIPT
flattenTree({
  id: "docs",
  children: [
    { id: "guide", title: "Guide", children: [{ id: "install" }] },
    { id: "api" },
  ],
});
// [
//   { id: "docs",    parentId: null,    depth: 0, path: ["docs"] },
//   { id: "guide",   title: "Guide", parentId: "docs", depth: 1, path: ["docs", "guide"] },
//   { id: "install", parentId: "guide", depth: 2, path: ["docs", "guide", "install"] },
//   { id: "api",     parentId: "docs",  depth: 1, path: ["docs", "api"] },
// ]
JAVASCRIPT
flattenTree([]);                                // []
flattenTree([{ id: 0, children: [{ id: 1 }] }]); // the second row has parentId 0
JAVASCRIPT
const node = { id: "x", children: [] };
node.children.push(node);
flattenTree(node); // throws TypeError

Environment

  • Plain JavaScript in a browser page; the tests call the global flattenTree from flatten-tree.js.
  • Rebuilding a tree from rows is not part of this problem.

Hints

  1. Besides the node, what does a recursive call need to know to fill in parentId, depth and path?
  2. Which nodes can make a cycle: every node seen so far, or only the ones you are still inside of?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…