Leetcode 1315. 祖父节点值为偶数的节点和 C++

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * 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 all = 0;
    int sumEvenGrandparent(TreeNode* root) {
            TreeNode* p = root;         
            Judgenode(p);
            return all;
    }
    void Judgenode(TreeNode* p){//判断p的左右孩子
        int num = p->val;
        if(p->left){
            Judge(p->left,num);//传入p的值和p的左孩子
            Judgenode(p->left);
        }
        if(p->right){
            Judge(p->right,num);//传入p的值和p的右孩子
            Judgenode(p->right);
        }
    }
    void Judge(TreeNode* p,int num){//传进来的是p的左或右孩子
        if(num%2 != 0){//判断祖父节点值是否为偶数
            return ;
        }
        if(p->left){//判断p的孙子结点
            all += p->left->val;
        }
        if(p->right){//判断p的孙子结点
            all += p->right->val;
        }
        return ;
    }
};
发布了20 篇原创文章 · 获赞 20 · 访问量 1739

猜你喜欢

转载自blog.csdn.net/qq_43320728/article/details/104820758
今日推荐