I want to shape the one-dimensional arrangement into a wooden structure.

Asked 1 years ago, Updated 1 years ago, 297 views

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:[])])
])

algorithm data-structure

2022-10-24 00:01

2 Answers

Assuming that the structure represented by the input data is a tree, you can calculate it by doing something like a depth-first search.

  • Without the stringing children, I would become a leaf (terminal node).In other words, children is [].
  • If there are children with strings attached, do step 3 for each and make the returned nodes children.


2022-10-24 00:01

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)
      }
    }
  }
}


2022-10-24 00:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.