This repository was archived by the owner on Apr 27, 2025. It is now read-only.
File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 404. Sum of Left Leaves
2
+
3
+ ### 2017-03-27
4
+
5
+ Find the sum of all left leaves in a given binary tree.
6
+
7
+ ** Example:**
8
+
9
+ ```
10
+ 3
11
+ / \
12
+ 9 20
13
+ / \
14
+ 15 7
15
+
16
+ There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
17
+ ```
18
+
19
+
20
+
21
+ # Solution
22
+
23
+ ``` swift
24
+ /**
25
+ * Definition for a binary tree node.
26
+ * public class TreeNode {
27
+ * public var val: Int
28
+ * public var left: TreeNode?
29
+ * public var right: TreeNode?
30
+ * public init(_ val: Int) {
31
+ * self.val = val
32
+ * self.left = nil
33
+ * self.right = nil
34
+ * }
35
+ * }
36
+ */
37
+ class Solution {
38
+ func sumOfLeftLeaves (_ root : TreeNode? ) -> Int {
39
+ guard let n = root else { return 0 }
40
+ var layer = [n]
41
+ var count = 0
42
+ while layer.count > 0 {
43
+ for i in 0 ..< layer.count {
44
+ let node = layer.removeFirst ()
45
+ if let l = node.left {
46
+ if l.left == nil && l.right == nil {
47
+ count += l.val
48
+ }
49
+ layer.append (l)
50
+ }
51
+ if let r = node.right {
52
+ layer.append (r)
53
+ }
54
+ }
55
+ }
56
+ return count
57
+ }
58
+ }
59
+ ```
60
+
You can’t perform that action at this time.
0 commit comments