Share my easy solution


  • 0

    I think this question is quite similar with question 104.

    func levelOrder(root: TreeNode?) -> [[Int]] {
        var q = [root]
        var result = [[Int]]()
        var level = 0
        while !q.isEmpty && q.first! != nil {
            let size = q.count
            var val = [Int]()
            for _ in 0..<size {
                let node = q.first!
                val.append((q.first!?.val)!)
                if node!.left != nil {
                    q.append(node?.left)
                }
                if node!.right != nil {
                    q.append(node?.right)
                }
                q.removeAtIndex(0)
            }
            level += 1
            result.append(val)
        }
        return result
    }
    

Log in to reply
 

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