forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sum_of_Left_Leaves.cpp
34 lines (33 loc) · 986 Bytes
/
Sum_of_Left_Leaves.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int sumOfLeftLeavesRecur(TreeNode* root, bool isLeft) {
if(!root) return 0;
if(!root->left and !root->right and isLeft) return root->val;
return sumOfLeftLeavesRecur(root->left, true) + sumOfLeftLeavesRecur(root->right, false);
}
public:
int sumOfLeftLeaves(TreeNode* root) {
return sumOfLeftLeavesRecur(root, false);
}
};
// Another approach without any helper method
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(!root) return 0;
if(root->left and (!root->left->left and !root->left->right)) {
return root->left->val
+ sumOfLeftLeaves(root->right);
}
return sumOfLeftLeaves(root->left)
+ sumOfLeftLeaves(root->right);
}
};