-
Notifications
You must be signed in to change notification settings - Fork 1
/
404.cpp
37 lines (34 loc) · 865 Bytes
/
404.cpp
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
#include <bits/stdc++.h>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;
dfs(root, 1, sum);
return sum;
}
void dfs(TreeNode* root, int flag, int& sum) {
// flag 0 左 1 右
if (root->left == nullptr && root->right == nullptr) {
if (flag == 0) sum += root->val;
return;
}
if (root->left != nullptr) dfs(root->left, 0, sum);
if (root->right != nullptr) dfs(root->right, 1, sum);
}
};