leetcode-cpp 1315.祖父节点值为偶数的节点和

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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43255713/article/details/105524581