我需要创建一个函数,以从树结构中的特定节点返回所有父节点。
这是结构示例:
struct Node
{
var name: String
var id: Int
var parentId: Int?
var children: [Node]
init(name: String, id: Int, children: [Node], parentId: Int?)
{
self.name = name
self.id = id
self.children = children
self.parentId = parentId
}
}
这将是一个Node数组。
Array(
Node("A1", 1, [
Node ("A11", 11, [
Node("A111", 111, []),
Node("A112", 112, [])
]
)]),
Node("A2", 2, [
Node ("A21", 21, [
Node("A211", 211, []),
Node("A212", 212, [])
]
)]),
)
)
如果我选择“ 112”,我应该得到一个这样的数组:
[Node("A1", 1, [...]), Node ("A11", 11, [...]]
有什么想法我该怎么做?
这是一个可测试的示例:
let nodeA111 = Node(name: "A111", id: 111, children: [], parentId: 11)
let nodeA112 = Node(name: "A112", id: 112, children: [], parentId: 11)
let nodeA211 = Node(name: "A211", id: 211, children: [], parentId: 21)
let nodeA212 = Node(name: "A212", id: 212, children: [], parentId: 21)
let nodeA11 = Node(name: "A11", id: 11, children: [nodeA111, nodeA112], parentId: 1)
let nodeA21 = Node(name: "A21", id: 21, children: [nodeA211, nodeA212], parentId: 2)
let nodeA1 = Node(name: "A1", id: 1, children: [nodeA11], parentId: nil)
let nodeA2 = Node(name: "A2", id: 2, children: [nodeA21], parentId: nil)
let nodes: [Node] = [nodeA1, nodeA2]
// This is the function I want to do
func getParentNodes(forNode node: Node) -> [Node]
{
return []
}
感谢您的帮助。