You are given a flat array of comment objects comments. Each object contains an id and a parentId, which is either the id of its parent comment or null for a root-level comment. Transform the array into a nested tree structure.
Each node in the resulting tree must contain the original fields plus a children array holding its direct child nodes, each of which recursively contains its own descendants.
Return an array of the root-level nodes (those whose parentId is null), with all descendants nested under them. The order of children follows the order in which they appear in the input array.
Function Signature
def build_comment_tree(comments: list[dict]) -> list[dict]:
Rules
-
Each comment is a dict with an integer
"id"
and a
"parentId"
that is either the id of another comment or
None
(the Python form of
null
) for a root comment. Any other keys a comment carries are copied into its node unchanged.
-
Each output node holds the comment's original fields plus a
"children"
list of its direct child nodes. A comment with no replies has
"children": []
.
-
The roots, and the children of every node, appear in the same relative order as in the input array.
-
The input does not guarantee that a parent appears before its children.
Constraints
-
0 <= len(comments) <= 10^4
-
Each comment has a unique
id
.
-
parentId
is either
None
or the
id
of another comment in the array.
-
The comment hierarchy contains no cycles.
Examples
Input: comments = [
{"id": 1, "parentId": None},
{"id": 2, "parentId": 1},
{"id": 3, "parentId": 1},
{"id": 4, "parentId": 2},
{"id": 5, "parentId": None}
]
Output: [
{"id": 1, "parentId": None, "children": [
{"id": 2, "parentId": 1, "children": [
{"id": 4, "parentId": 2, "children": []}
]},
{"id": 3, "parentId": 1, "children": []}
]},
{"id": 5, "parentId": None, "children": []}
]
Comments 1 and 5 are roots, listed in input order. Comments 2 and 3 are replies to 1 (2 comes first because it appears first), and 4 is a reply to 2.
Input: comments = [
{"id": 10, "parentId": None},
{"id": 20, "parentId": 10},
{"id": 30, "parentId": 20},
{"id": 40, "parentId": 30}
]
Output: [
{"id": 10, "parentId": None, "children": [
{"id": 20, "parentId": 10, "children": [
{"id": 30, "parentId": 20, "children": [
{"id": 40, "parentId": 30, "children": []}
]}
]}
]}
]
There is a single root, and each later comment replies to the one before it, so the result is one chain four levels deep.
Input: comments = [
{"id": 7, "parentId": 3},
{"id": 3, "parentId": None},
{"id": 9, "parentId": 3}
]
Output: [
{"id": 3, "parentId": None, "children": [
{"id": 7, "parentId": 3, "children": []},
{"id": 9, "parentId": 3, "children": []}
]}
]
Comment 7 appears before its parent 3 but still ends up under it. Both replies keep their input order, so 7 comes before 9.