-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathday-146.cpp
More file actions
38 lines (28 loc) · 745 Bytes
/
day-146.cpp
File metadata and controls
38 lines (28 loc) · 745 Bytes
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
/*
Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively.
Return 24.
*/
// Solved using recursion, O(N) time & O(1) memory usage
class Solution {
public:
void leftLeavesHelper(TreeNode* root, int& sum, int flag) {
if (root == NULL) return;
if (flag == 1 && root->left == NULL && root->right == NULL)
sum += root->val;
leftLeavesHelper(root->left, sum, 1);
leftLeavesHelper(root->right, sum, 2);
}
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;
leftLeavesHelper(root, sum, 0);
return sum;
}
};