给你一棵二叉树,请你返回满足以下条件的所有节点的值之和:该节点的祖父节点的值为偶数。(一个节点的祖父节点是指该节点的父节点的父节点。)如果不存在祖父节点值为偶数的节点,那么返回 0 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-nodes-with-even-valued-grandparent
思想:可以转换成某个偶数节点的子节点的子节点的和问题。由于不知道树中节点最大数量,层序遍历时用到队列的顺序存储结构不易实现,使用先根遍历会更方便。先根遍历寻找值为偶数的节点,判断其是否有孙子节点,将孙子节点的值加到求和器count中。遍历完整个数组,count值也就求出了。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int sumEvenGrandparent(struct TreeNode* root);
int rootFirst(struct TreeNode* root, int count);
int getCount(struct TreeNode* root);
int sumEvenGrandparent(struct TreeNode* root){
return rootFirst(root, 0);
}
int rootFirst(struct TreeNode* root, int count){
if (root->val % 2 == 0){
count += getCount(root);
}
if(root->left != NULL) count = rootFirst(root->left, count);
if(root->right != NULL) count = rootFirst(root->right, count);
return count;
}
int getCount(struct TreeNode* root){
int count = 0;
if(root->left != NULL){
if(root->left->left != NULL) count += root->left->left->val;
if(root->left->right != NULL) count += root->left->right->val;
}
if(root->right != NULL){
if(root->right->left != NULL) count += root->right->left->val;
if(root->right->right != NULL) count += root->right->right->val;
}
return count;
}