Skip to content

Instantly share code, notes, and snippets.

@lishunan246
Created August 24, 2020 16:42
Show Gist options
  • Save lishunan246/a7e884a1e878b303268413bb0f1985b5 to your computer and use it in GitHub Desktop.
Save lishunan246/a7e884a1e878b303268413bb0f1985b5 to your computer and use it in GitHub Desktop.
Sum of Left Leaves
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
int s(TreeNode* root) {
int sum = 0;
if (root->left) {
if (root->left->left == nullptr && root->left->right == nullptr) {
sum += root->left->val;
}
else {
sum += s(root->left);
}
}
if (root->right) {
sum += s(root->right);
}
return sum;
}
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr) {
return 0;
}
return s(root);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment