Implementing recursive generator for simple tree structure in Swift

前端 未结 3 600
半阙折子戏
半阙折子戏 2021-01-13 18:36

I have a simple tree structure in memory based on an XML document and I am trying to write a recursive generator to support SequenceType, but I am stuck on how

3条回答
  •  悲&欢浪女
    2021-01-13 19:20

    I don't know if a generator itself can be recursive. Will M proved me wrong!

    Here is a possible implementation for a pre-order traversal, using a stack for the child nodes which still have to be enumerated:

    extension XMLNode : SequenceType {
        public func generate() -> AnyGenerator {
            var stack : [XMLNode] = [self]
            return anyGenerator {
                if let next = stack.first {
                    stack.removeAtIndex(0)
                    stack.insertContentsOf(next.childNodes, at: 0)
                    return next
                }
                return nil
            }
        }
    }
    

    For a level-order traversal, replace

    stack.insertContentsOf(next.childNodes, at: 0)
    

    by

    stack.appendContentsOf(next.childNodes)
    

提交回复
热议问题