ac solution code


  • 0
    /*
         Solution1. time = O(n); space = O(n)
         The basic idea is using BFS to traverse the tree level by level. The little trick is to get the current count of the queue first, then loop though the current level up to count, so that we can reuse the queue.
         */
        func levelOrder(_ root: TreeNode?) -> [[Int]] {
            var res = [[Int]]()
            guard let root = root else {return res}
            var queue = Queue<TreeNode>()
            queue.offer(root)
    
            while !queue.isEmpty() {            // BFS loop
                let count = queue.size
                var oneLevel = [Int]()
                for _ in 0 ..< count {          // Loop though the current level up to count to reuse queue
                    let node = queue.poll()!    // Dequeue the first node
                    oneLevel.append(node.val)   // Append node's val to oneLevel
                    if let left = node.left {   // Enqueue node's left
                        queue.offer(left)
                    }
                    if let right = node.right { // Enqueue node's right
                        queue.offer(right)
                    }
                }
                res.append([Int](oneLevel))     // Append oneLevel to res
            }
            return res
        }
    

    0_1485216628265_Evernote Camera Roll 20170123 160848.jpg


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.