Challenge:
Convert a flat representation of a hierarchical data into a nested tree structure.
Assumptions:
- The dataset is already sorted
- The dataset should be in the form of an RDBMS resultset, however that is represented in your target language
- Multiple "top-level" nodes may exist, defined as having an empty parentId
Expectations:
- Result is an array of the top level nodes, with child nodes nested below them.
- Use the key
children
to assign an array of child nodes to the parent. - A node that does not have any children should not have the
children
key.
Examples:
dataset:
id | parentId | nodeText |
---|---|---|
1 | null | File |
2 | 1 | New |
3 | 2 | File |
4 | 2 | Folder |
5 | null | Edit |
6 | 5 | Copy |
7 | 5 | Cut |
8 | 5 | Paste |
9 | null | Help |
10 | 9 | About |
Expected result:
[
{
nodeText : "File"
,children : [
{
nodeText : "New"
,children : [
{ nodeText: "File" }
,{ nodeText: "Folder" }
]
}
]
}
,{
nodeText : "Edit"
,children : [
{nodeText: "Copy"}
,{nodeText: "Cut"}
,{nodeText: "Paste"}
]
}
,{
nodeText : "Help"
,children : [
{ nodeText: "About" }
]
}
]
Judging
- Correctness of the result. The solution must address the problem as specified.
- Readability. This is not code golf - conciseness is good, but readable/understandable/maintainable is the goal.
- Bonus: sharing test cases in the comments on the gist are appreciated by everyone!
Rules
- Original work only
- Submissions should be licensed under a permissive license (MIT/BSD/Apache 2.0/etc.)
- You can use any language
- This is for fun and learning. There are no prizes except pride, knowledge and maybe karma.
- Submit answers in the comments as Gist/PasteBin/Online REPL, not in slack.
- If you need to clarify something about the problem or rules, do it in the comments on the gist, or at least copy the clarification there for posterity
This comment has been minimized.
Do we post answers here? https://github.com/CraicOverflow89/FridayPuzzle/blob/master/26082016.cfm