
思路:先序遍历
代码片段
/**
* 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 sumEvenGrandparent(TreeNode* root) {
int res = 0;
if (root) {
if (root -> val % 2 == 0) {
if (root -> left) {
if (root -> left -> left) {
res += root -> left -> left -> val;
}
if (root -> left -> right) {
res += root -> left -> right -> val;
}
}
if (root -> right) {
if (root -> right -> left) {
res += root -> right -> left -> val;
}
if (root -> right -> right) {
res += root -> right -> right -> val;
}
}
}
if (root -> left) res += sumEvenGrandparent(root -> left);
if (root -> right) res += sumEvenGrandparent(root -> right);
}
return res;
}
};
网友评论