Algorithm 在Swift 3中过滤复杂的嵌套数组

Algorithm 在Swift 3中过滤复杂的嵌套数组,algorithm,swift3,Algorithm,Swift3,我有一个复杂的数组(树),如下所示: [0] code = "pc1" children [0] code = "gc1" children [0] code = "cc1" children = nil [1] code = "cc2" children = nil [1] code = "gc2"

我有一个复杂的数组(树),如下所示:

[0] code = "pc1"
    children
      [0] code = "gc1"
          children
              [0] code = "cc1"
                  children = nil
              [1] code = "cc2"
                  children = nil
      [1] code = "gc2"
          children = nil
[1] code = "pc2"
    children = nil
我想要的是搜索任何没有子节点的节点。如果发现任何子注释,我希望保留层次结构。例如,搜索“2”将返回以下内容:

[0] code = "pc1"
    children
      [0] code = "gc1"
          children
              [0] code = "cc2"
                  children = nil
      [1] code = "gc2"
          children = nil
[1] code = "pc2"
    children = nil
搜索“p”将返回:

[0] code = "pc1"
    children
[1] code = "pc2"
    children = nil
我试了很长时间。但没有找到解决办法。有什么想法吗?谢谢

于2017年8月27日编辑:

这是我的树类:

class Node {

  var parentCode: String = ""

  weak var parent: Node?
  lazy var children = [Node]()

  init() {}

  func add(node: Node) {
    children.append(code)
    code.parent = self
  }


如果我想搜索字母o

,这将是结果。实际上,这是一个关于树过滤的问题。我建造了我的树结构。任何算法都能做到这一点?实际上这是一个关于树过滤的问题。我建造了我的树结构。任何算法都能做到这一点?