【发布时间】:2017-09-22 18:56:29
【问题描述】:
使用 swift 实现 Tree 数据结构:
class Node {
var value: String
var children: [Node] = []
weak var parent: Node?
init(_ value: String) {
self.value = value
}
func add(_ child: Node){
children.append(child)
child.parent = self
}
func printTree() {
var text = self.value
if !self.children.isEmpty {
text += "\n " + self.children.map{$0.printTree()}.joined(separator: ", ")
}
print(text)
}
}
我的目标是看到这样的东西:
A1
B2
C3
G6
K0
H7
L8
L9
我知道应该有一些聪明的方法来插入缩进,但我也为“地图”而苦恼。编译器给了我“对成员 'map' 的模棱两可的引用”。
【问题讨论】:
-
代替(或附加于)
printTree()方法,您可以实现CustomStringConvertible的description方法,然后您可以使用print(node)打印树
标签: swift data-structures tree