Skip to content

Commit ae1443c

Browse files
author
Yi Gu
committed
[Tree] add a solution to Sum of Left Leaves
1 parent 6649eff commit ae1443c

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Tree/SumLeftLeaves.swift

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

0 commit comments

Comments
 (0)