Skip to content

Commit fe7aca5

Browse files
authored
Create sum-of-left-leaves.cpp
1 parent 52addbf commit fe7aca5

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

C++/sum-of-left-leaves.cpp

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Time: O(n)
2+
// Space: O(h)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
int sumOfLeftLeaves(TreeNode* root) {
16+
return sumOfLeftLeavesHelper(root, false);
17+
}
18+
19+
private:
20+
int sumOfLeftLeavesHelper(TreeNode* root, bool is_left) {
21+
if (!root) {
22+
return 0;
23+
}
24+
if (!root->left && !root->right) {
25+
return is_left ? root->val : 0;
26+
}
27+
return sumOfLeftLeavesHelper(root->left, true) +
28+
sumOfLeftLeavesHelper(root->right, false);
29+
}
30+
};

0 commit comments

Comments
 (0)