美文网首页
二叉树层序遍历

二叉树层序遍历

作者: 周一见丶 | 来源:发表于2022-10-25 18:37 被阅读0次

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

    class Solution {
        func levelOrder(_ root: TreeNode?) -> [[Int]] {
            guard let root = root else { return [] }
            let queue = LoopQueue<TreeNode>()
            var result = Array<Array<Int>>()
            queue.enqueue(element: root)
            
            while queue.isEmpty() == false {
                var cengJiResult = Array<Int>()
                for _ in 0..<queue.getSize() {
                    let now = queue.dequeue()
                    cengJiResult.append(now.val)
                    if let left = now.left {
                        queue.enqueue(element: left)
                    }
                    if let right = now.right {
                        queue.enqueue(element: right)
                    }
                }
                result.append(cengJiResult)
            }
            
            return result
        }
    }
    
    protocol Queue {
        associatedtype ItemType
        
        func getSize() -> Int
        func isEmpty() -> Bool
        func enqueue(element: ItemType)
        func dequeue( ) -> ItemType
        func getFront() -> ItemType
    }
    
    class LoopQueue<T>: CustomStringConvertible, Queue {
        private var array: Array<T?>
        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<T?>.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<T?>.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

    相关文章

      网友评论

          本文标题:二叉树层序遍历

          本文链接:https://www.haomeiwen.com/subject/hkfzzrtx.html