1315.祖父节点值为偶数的节点和
-
链接
leetcode
-
solution:
BFS 用最蠢的方式
-
code
class Solution {
public:
int sumEvenGrandparent(TreeNode* root) {
int res=0;
queue<TreeNode* >q;
q.push(root);
while(!q.empty()){
int len=q.size();
while(len--){
TreeNode* t=q.front();
q.pop();
if(t->left&&t->val%2==0){
if(t->left->left) res+=t->left->left->val;
if(t->left->right) res+=t->left->right->val;
}
if(t->right&&t->val%2==0){
if(t->right->left) res+=t->right->left->val;
if(t->right->right) res+=t->right->right->val;
}
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
}
return res;
}
};