Swift Solution


  • 0
    C
    class Solution {
        
        func levelOrder(_ root: TreeNode?) -> [[Int]] {
            guard let root = root else { return [[Int]]() }
            
            var dict = [Int: [Int]]()
            
            func order(node: TreeNode?, level: Int) {
                if let node = node {
                    if let _ = dict[level] {
                        dict[level]!.append(node.val)
                    }else {
                        dict[level] = [node.val]
                    }
                    order(node: node.left, level: level+1)
                    order(node: node.right, level: level+1)
                }
            }
            
            order(node: root, level: 0)
            
            return dict.sorted(by: {$0.0 < $1.0}).map({$0.1})
        }
        
    }
    

Log in to reply
 

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