swift - 打印带有缩进的树。 swift

标签 swift data-structures tree

使用 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/

相关文章:

ios - 访问 Realms 对象列表时出错 : Realm accessed from incorrect thread

ios - 调试 Swift 代码时,我能否仅根据对象的地址获得对象的类型化引用?

javascript - 有向无环层次图实现

swift - 何时注销 KVO Operation isFinished 观察

ios - 从 firebase 中检索金额值使用 swift 3 进行减法和更新金额

java - Map<Object, Collection<Object>> 有什么问题?

python - 是否可以限制仅使用不同类中的 setter/modifier 方法?

python - 计算最多具有m个偶数元素的不同子数组的数量

algorithm - 从中序和前序重建二叉树

Python:加入和写入(XML.etrees)存储在列表中的树