计算给定二叉树的所有左叶子之和。
示例:
3
/ \
9 20
/ \
15 7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-left-leaves
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* 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 {
public:
int ret;
set<int> myset;
int sumOfLeftLeaves(TreeNode* root)
{
ret = 0;
bianli(root);
cal(root);
return ret;
}
void bianli(TreeNode* root)
{
if(root != NULL)
{
if(root->left == NULL && root->right == NULL)
{
myset.insert(root->val);
}
bianli(root->left);
bianli(root->right);
}
}
void cal(TreeNode* root)
{
if(root != NULL)
{
if(root->left != NULL)
{
if(myset.find(root->left->val) != myset.end() && root->left->left == NULL && root->left->right == NULL)
{
ret += root->left->val;
}
}
cal(root->left);
cal(root->right);
}
}
};