祖父節點值爲偶數的節點和
由於需要知道祖父節點的值,所以搜索的時候要帶着祖父節點、父親節點、以及當前節點。
/**
* 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 ans=0;
int sumEvenGrandparent(TreeNode* root) {
dfs(nullptr,nullptr,root);
return ans;
}
void dfs(TreeNode* gp,TreeNode* par,TreeNode* cur){
if(!cur) return;
if(gp && gp->val % 2==0){
ans+=cur->val;
}
dfs(par,cur,cur->left);
dfs(par,cur,cur->right);
}
};