Swift solution - BFS(Queue), DFS(recursive)


  • 0
    class Solution {
        func levelOrder(_ root: TreeNode?) -> [[Int]] {
            guard let root = root else {
                return []
            }
            
            var queue = [TreeNode]()
            var result = [[Int]]()
            
            queue.append(root)
            while !queue.isEmpty {
                let levelCount = queue.count
                var levelNodes = [Int]()
                for _ in 0..<levelCount {
                    let node = queue.removeFirst()
                    if let leftNode = node.left {
                        queue.append(leftNode)
                    }
                    if let rightNode = node.right {
                        queue.append(rightNode)
                    }
                    levelNodes.append(node.val)
                }
                result.append(levelNodes)
            }
            
            return result
        }
        
        func levelOrder_DFS(_ root: TreeNode?) -> [[Int]] {
            guard let root = root else {
                return []
            }
            
            var result = [[Int]]()
            helper(&result, root, 0)
            return result
        }
        
        func helper(_ result: inout [[Int]], _ root: TreeNode?, _ height: Int) {
            guard let root = root else {
                return
            }
            
            if height >= result.count {
                result.append([Int]())
            }
            result[height].append(root.val)
            helper(&result, root.left, height + 1)
            helper(&result, root.right, height + 1)
        }
    }
    

Log in to reply
 

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