二叉树层序遍历

层序遍历是一层一层访问,利用队列先进先出的性质,和先序遍历类似,如果把每一层分开,需要通过一个循环将这层的节点都出队

class Solution {
    func levelOrder(_ root: TreeNode?) -> [[Int]] {
        guard let root = root else { return [] }
        let queue = LoopQueue()
        var result = Array>()
        queue.enqueue(element: root)
        
        while queue.isEmpty() == false {
            var cengJiResult = Array()
            for _ in 0.. Int
    func isEmpty() -> Bool
    func enqueue(element: ItemType)
    func dequeue( ) -> ItemType
    func getFront() -> ItemType
}

class LoopQueue: CustomStringConvertible, Queue {
    private var array: Array
    private var front = 0
    private var tail = 0
    private var size = 0
    
    var description: String {
        var des = "front ["
        var i = front
        while i != tail {
            des += String(describing: array[i])
            if i != (tail - 1) {
                des += ", "
            }
            i = (i + 1) % array.count
        }
        des += "] tail"
        return des
    }
    
    init(capacity: Int) {
        array = Array.init(repeating: nil, count: capacity)
    }
    
    convenience init() {
        self.init(capacity: 10)
    }
    
    //MARK: - Stack
    func getSize() -> Int {
        return size
    }
    
    func getCapacity() -> Int {
        return array.count - 1
    }
    
    func isEmpty() -> Bool {
        return front == tail
    }
    
    func enqueue(element: T) {
        if size == getCapacity() {
            resize(capacity: getCapacity() * 2)
        }
        array[tail] = element
        tail = (tail + 1) % array.count
        size += 1
    }
    
    func dequeue() -> T {
        if isEmpty() {
            fatalError("Queue is Empty")
        } else {
            if size == (getCapacity() / 4) {
                resize(capacity: getCapacity() / 2)
            }
            let t = array[front]!
            array[front] = nil
            front = (front + 1) % array.count
            size -= 1
            return t
        }
    }
    
    func getFront() -> T {
        if isEmpty() {
            fatalError("Queue is Empty")
        } else {
            return array[front]!
        }
    }
    
    private func resize(capacity: Int) {
        var newArray = Array.init(repeating: nil, count: capacity + 1)
        for i in 0 ..< size {
            newArray[i] = array[(front + i) % array.count]
        }
        front = 0
        tail = size
        array = newArray
    }
}

流程图

IMG_1750.jpg

你可能感兴趣的:(二叉树层序遍历)