I would like to have OriginalData with my ID and parent ID in the form of a tree structure.
I want to convert inputDatas
to the form result
I want to do recursive work, but I can't think of a good way.
Any language in particular is fine.
structure OriginalData{
let id —String
let parentID—String?
}
US>structure Node {
let id —String
varchildren —Node.
}
let inputData: OriginalData = [
.init(id:"1", parentID:nil),
.init(id: "2", parentID: "1"),
.init(id:"3", parentID:"2"),
.init(id: "4", parentID: "1"),
.init(id: "5", parentID: "4"),
]
let result=Node(id:"1", children:[
Node(id:"2", children:[Node(id:"3", children:[]),
Node(id:"4", children:[Node(id:"5", children:[])])
])
Assuming that the structure represented by the input data is a tree, you can calculate it by doing something like a depth-first search.
children
is []
.children
.
extension Node {
mutating funcaddChild(allData: [OriginalData]){
for i in children.indices {
children[i].children=allData.filter {children[i].id==$0.parentID}.map{.init(id:$0.id,children:[])}
for jin children.indices {
children[j].addChild(allData:allData)
}
}
}
}
© 2024 OneMinuteCode. All rights reserved.