forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SumLeftLeaves.swift
43 lines (38 loc) · 1.1 KB
/
SumLeftLeaves.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Question Link: https://leetcode.com/problems/sum-of-left-leaves/
* Primary idea: Recursion. Go to left and right and add to res if it is left leaf.
* Time Complexity: O(n), Space Complexity: O(1)
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class SumLeftLeaves {
func sumOfLeftLeaves(_ root: TreeNode?) -> Int {
guard let root = root else {
return 0
}
var res = 0
helper(root.left, true, &res)
helper(root.right, false, &res)
return res
}
private func helper(_ node: TreeNode?, _ isLeft: Bool, _ res: inout Int) {
guard let node = node else {
return
}
if node.left == nil && node.right == nil && isLeft {
res += node.val
}
helper(node.left, true, &res)
helper(node.right, false, &res)
}
}