Swift solution - BFS + Queue, DFS recursive


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

Log in to reply
 

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