当前位置: 代码迷 >> 综合 >> Leetcode 1315. 祖父节点值为偶数的节点和(DAY 7)
  详细解决方案

Leetcode 1315. 祖父节点值为偶数的节点和(DAY 7)

热度:32   发布时间:2023-11-17 20:40:30.0

原题题目

在这里插入图片描述




代码实现(首刷自解)

/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/#define MAX 10001int count(struct TreeNode* arr[],int* size)
{
    int sum = 0,i;if((*size)){
    for(i=0;i<(*size);i++){
    if(arr[i]->left){
    if(arr[i]->left->left) sum += arr[i]->left->left->val;if(arr[i]->left->right) sum += arr[i]->left->right->val;}if(arr[i]->right){
    if(arr[i]->right->left) sum += arr[i]->right->left->val;if(arr[i]->right->right) sum += arr[i]->right->right->val;}}}return sum;
}void visit(struct TreeNode* arr[],int *size,struct TreeNode* root)
{
    if(root){
    visit(arr,size,root->left);visit(arr,size,root->right);if(root->val % 2 == 0)arr[(*size)++] = root;}
}int sumEvenGrandparent(struct TreeNode* root){
    struct TreeNode* arr[MAX];int size = 0,sum = 0;visit(arr,&size,root);sum = count(arr,&size);return sum;
}