Swift solution - BFS


  • 0
    class Solution {
        func sumOfLeftLeaves(_ root: TreeNode?) -> Int {
            guard let root = root else {
                return 0
            }
            
            var result = 0
            var queue = [TreeNode]()
            
            queue.append(root)
            while !queue.isEmpty {
                let node = queue.removeFirst()
                if let leftNode = node.left {
                    if leftNode.left == nil && leftNode.right == nil {
                        result += leftNode.val
                    } else {
                        queue.append(leftNode)
                    }
                }
                if let rightNode = node.right {
                    if rightNode.left != nil || rightNode.right != nil {
                        queue.append(rightNode)
                    }
                }
            }
            
            return result
        }
    }
    

Log in to reply
 

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