解题思路:
(1)保存父节点和祖父节点
(2)判断祖父节点是否是偶数
/**
* 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) {}
* };
*/
class Solution {
private:
int sum = 0;
public:
void preorder(TreeNode *root,TreeNode *pa, TreeNode *ga) {
if(root!=NULL) {
if(pa!=NULL && ga!=NULL && ga->val%2==0) sum+=root->val;
preorder(root->left,root,pa);
preorder(root->right,root,pa);
}
}
int sumEvenGrandparent(TreeNode* root) {
TreeNode *pa=NULL, *ga=NULL;
preorder(root,pa,ga);
return sum;
}
};