classSolution{public:intsumEvenGrandparent(TreeNode*root){returndfs(root,1,1);// The parent and the grandparent are odd at first.}private:intdfs(TreeNode*root,intp,intgp){if(root==nullptr)return0;return(gp%2==0?root->val:0)+//dfs(root->left,root->val,p)+//dfs(root->right,root->val,p);}};
1 2 3 4 5 6 7 8 910111213
classSolution{publicintsumEvenGrandparent(TreeNoderoot){returndfs(root,1,1);// The parent and the grandparent are odd at first.}privateintdfs(TreeNoderoot,intp,intgp){if(root==null)return0;return(gp%2==0?root.val:0)+//dfs(root.left,root.val,p)+//dfs(root.right,root.val,p);}}