Swift solution - DFS


  • 0
    class Solution {
        func sumOfLeftLeaves(_ root: TreeNode?) -> Int {
            guard let root = root else {
                return 0
            }
            
            var result = 0
            
            if let leftNode = root.left {
                if leftNode.left == nil && leftNode.right == nil {
                    result += leftNode.val
                } else {
                    result += sumOfLeftLeaves(leftNode)
                }
            }
            result += sumOfLeftLeaves(root.right)
            
            return result
        }
    }
    

Log in to reply
 

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