使用 swift 实现树数据结构:
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 ”作斗争。编译器给我“对成员‘map’的模糊引用”。
最佳答案
如果你想让它漂亮,你可以这样做:
extension Node
{
func treeLines(_ nodeIndent:String="", _ childIndent:String="") -> [String]
{
return [ nodeIndent + value ]
+ children.enumerated().map{ ($0 < children.count-1, $1) }
.flatMap{ $0 ? $1.treeLines("┣╸","┃ ") : $1.treeLines("┗╸"," ") }
.map{ childIndent + $0 }
}
func printTree()
{ print(treeLines().joined(separator:"\n")) }
}
a1.printTree()
// A1
// ┣╸B2
// ┣╸C3
// ┃ ┗╸G6
// ┗╸K0
// ┣╸H7
// ┃ ┗╸L8
// ┗╸L9
您还可以将其概括为任何树结构的打印函数,让您选择为每个节点打印什么:
func printTree<T>(_ node:T, _ nodeInfo:@escaping (T)->(String,[T]) )
{
func lines(_ aNode:T, _ nodeIndent:String="", _ childIndent:String="") -> [String]
{
let (label,children) = nodeInfo(aNode)
return [ nodeIndent + label]
+ children.enumerated().map{ ($0 < children.count-1, $1) }
.flatMap{ $0 ? lines($1,"┣╸","┃ ") :lines($1,"┗╸"," ") }
.map{ childIndent + $0 }
}
print( lines(node).joined(separator:"\n") )
}
// print a root node providing a capture to obtain the node's label
// and its array of children
printTree(a1){ ($0.value,$0.children) }
// works for any tree structure. for example, views :
printTree(view){( "\(type(of:$0)) \($0.frame)", $0.subviews )}
关于swift - 打印带有缩进的树。 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46371513/