Flat List to Tree

ObjectsTreesInterview Question

Given a flat list of { id, name, parentId }, write buildTree(items) returning the roots of a tree.

Every node carries a children array. parentId is null for a root. Roots come back in the order they appeared. A child may be listed before its parent.

Examples

Example 1
Input
buildTree([
  { id: 1, name: 'Parent', parentId: null },
  { id: 2, name: 'Child', parentId: 1 },
]);
Output
[{ id: 1, name: 'Parent', parentId: null,
   children: [{ id: 2, name: 'Child', parentId: 1, children: [] }] }]
Explanation
The child is nested under the node whose id its parentId names.

Constraints

  • 0 <= items.length <= 10^4
  • ids are unique

Notes

  • Build the id lookup first and link second, so ordering in the input does not matter.
  • Spread each item into a new node rather than mutating the caller’s objects.

Hints

Read the full write-up for Flat List to Tree
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it