Swift solution - BFS, DFS


  • 0
    class Solution {
        func levelOrderBottom(_ root: TreeNode?) -> [[Int]] {
            guard let root = root else {
                return []
            }
            
            var levelLists = [[Int]]()
            var queue = [TreeNode]()
            
            queue.append(root)
            while !queue.isEmpty {
                var levelList = [Int]()
                let count = queue.count
                for _ in 0..<count {
                    let node = queue.removeFirst()
                    levelList.append(node.val)
                    if let leftNode = node.left {
                        queue.append(leftNode)
                    }
                    if let rightNode = node.right {
                        queue.append(rightNode)
                    }
                }
                levelLists.insert(levelList, at: 0)
            }
            
            return levelLists
        }
        
        func levelOrderBottom_DFS(_ root: TreeNode?) -> [[Int]] {
            guard let root = root else {
                return []
            }
            
            var levelLists = [[Int]]()
            
            helper(&levelLists, root, 0)
            
            return levelLists
        }
        
        func helper(_ levelLists: inout [[Int]], _ root: TreeNode?, _ level: Int) {
            guard let root = root else {
                return
            }
            
            if level >= levelLists.count {
                levelLists.insert([Int](), at: 0)
            }
            
            helper(&levelLists, root.left, level + 1)
            helper(&levelLists, root.right, level + 1)
            
            levelLists[levelLists.count - level - 1].append(root.val)
        }
    }
    

Log in to reply
 

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