Skip to content

Commit 33f05a2

Browse files
committed
feat: Solution for August Challenge 24 - Sum of Left Leaves
1 parent f765b38 commit 33f05a2

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/*:
2+
# Sum of Left Leaves
3+
https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/552/week-4-august-22nd-august-28th/3435/
4+
5+
---
6+
7+
### Problem Statement:
8+
9+
Find the sum of all left leaves in a given binary tree.
10+
11+
### Example:
12+
13+
```
14+
3
15+
/ \
16+
9 20
17+
/ \
18+
15 7
19+
20+
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
21+
22+
```
23+
*/
24+
25+
26+
import UIKit
27+
28+
29+
// Definition for a binary tree node.
30+
public class TreeNode {
31+
public var val: Int
32+
public var left: TreeNode?
33+
public var right: TreeNode?
34+
public init() { self.val = 0; self.left = nil; self.right = nil; }
35+
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
36+
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
37+
self.val = val
38+
self.left = left
39+
self.right = right
40+
}
41+
}
42+
43+
44+
class Solution {
45+
private var sum = 0
46+
func sumOfLeftLeaves(_ root: TreeNode?) -> Int {
47+
guard let node = root else {
48+
return 0
49+
}
50+
dfs(node, false)
51+
return sum
52+
}
53+
54+
private func dfs(_ node: TreeNode?, _ isLeft: Bool) {
55+
guard let node = node else { return }
56+
57+
dfs(node.left, true)
58+
59+
if node.left == nil, node.right == nil, isLeft {
60+
sum += node.val
61+
}
62+
dfs(node.right, false)
63+
}
64+
}
65+
66+
class Solution2 {
67+
68+
func sumOfLeftLeaves(_ root: TreeNode?) -> Int {
69+
return dfs(root, false)
70+
}
71+
72+
private func dfs(_ node: TreeNode?, _ isLeft: Bool) -> Int {
73+
guard let node = node else { return 0 }
74+
75+
if node.left == nil, node.right == nil, isLeft {
76+
return node.val
77+
}
78+
79+
return dfs(node.left, true) + dfs(node.right, false)
80+
}
81+
}
82+
83+
let node = TreeNode(3)
84+
node.left = TreeNode(9)
85+
node.right = TreeNode(20)
86+
node.right?.left = TreeNode(15)
87+
node.right?.right = TreeNode(7)
88+
89+
let sol = Solution2()
90+
sol.sumOfLeftLeaves(node) // 24
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

0 commit comments

Comments
 (0)