class Solution {
/* 本质上使用了一个层次遍历的方法,在层次遍历中找到左叶子结点,然后将其值增加到一个变量中
*/
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr) return 0;
int sum = 0;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
TreeNode* tmp = q.front();
q.pop();
// 条件判断 首先要保证tmp->left是存在的
if (tmp->left && tmp->left->left == nullptr && tmp->left->right == nullptr) {
sum = sum + tmp->left->val;
}
if (tmp->left) q.push(tmp->left);
if (tmp->right) q.push(tmp->right);
}
return sum;
}
};
// class Solution {
// public:
// int sumOfLeftLeaves(TreeNode* root) {
// if (root == nullptr)
// return 0;
// int val = 0;
// if (root->left && root->left->left == nullptr && root->left->right == nullptr)
// //这里思考不周全 只是去注意框架了 没有注意一个节点的右子树也存在左叶子节点
// return root->left->val + sumOfLeftLeaves(root->right);
// }
// return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
// }
// };