Swift solution - DFS, BFS


  • 0
    class Solution {
        func largestValues(_ root: TreeNode?) -> [Int] {
            var result = [Int]()
            DFS(root, &result, 0)
            return result
        }
        
        func DFS(_ root: TreeNode?, _ result: inout [Int], _ depth: Int) {
            guard let root = root else {
                return
            }
            
            if depth == result.count {
                result.append(root.val)
            } else {
                result[depth] = max(result[depth], root.val)
            }
            
            DFS(root.left, &result, depth + 1)
            DFS(root.right, &result, depth + 1)
        }
        
        func largestValues_BFS(_ root: TreeNode?) -> [Int] {
            guard let root = root else {
                return []
            }
            
            var result = [Int]()
            var queue = [TreeNode]()
            
            queue.append(root)
            while !queue.isEmpty {
                let size = queue.count
                var maxValue = Int.min
                for _ in 0..<size {
                    let node = queue.removeFirst()
                    maxValue = max(maxValue, node.val)
                    if let leftNode = node.left {
                        queue.append(leftNode)
                    }
                    if let rightNode = node.right {
                        queue.append(rightNode)
                    }
                }
                result.append(maxValue)
            }
            
            return result
        }
    }
    

Log in to reply
 

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