Junior — Senior
Converting a flat array into a nested tree hierarchy
livecode
Task condition
Given a linear array of elements representing tree nodes. Each element contains a unique identifier id and a reference to its parent node parent, which can be null (root node) or point to the id of another element. The task is to assemble a complete tree of arbitrary depth, placing child elements inside the children array of their parent.
/**
* @param array{int, array{id: int, name: string, parent: ?int}} $flatList
*
* @return array{int, array{id: int, name: string, parent: ?int, children: array{int, array}}}
*/
function mapTree(array $flatList): array
{
// implement conversion here
}
function testBuildTree(): void
{
$source = [
0 => ['id' => 0, 'parent' => null], // root
1 => ['id' => 1, 'parent' => null], // root
2 => ['id' => 2, 'parent' => 1], // child of 1
3 => ['id' => 3, 'parent' => 1], // child of 1
4 => ['id' => 4, 'parent' => 2], // grandchild of 1
5 => ['id' => 5, 'parent' => 4], // great-grandchild of 1
];
$resultTree = [
0 => ['id' => 0, 'parent' => null],
1 => [
'id' => 1, 'parent' => null, 'children' => [
0 => ['id' => 2, 'parent' => 1, 'children' => [
0 => ['id' => 4, 'parent' => 2, 'children' => [
0 => ['id' => 5, 'parent' => 4],
]],
]],
1 => ['id' => 3, 'parent' => 1],
],
],
];
assert(mapTree($source) === $resultTree);
}
testBuildTree();