Leetcode 1315. 祖父节点值为偶数的节点和 题解

题目链接:https://leetcode-cn.com/problems/sum-of-nodes-with-even-valued-grandparent/
在这里插入图片描述
在这里插入图片描述
第一眼看到就想到用两个bool值参数。因为一般的DFS都是一个参数标记状态,这次要考虑祖父节点,所以用两个参数 t1 和 t2,更新如下:

若当前 t2 为 true,说明其祖父节点为偶数,res += root->val,更新t2 = false
若当前 t1 为 true,说明其父节点为偶数,标记t2 = true, t1 = false
若当前节点值为偶数,则标记 t1 = true

代码如下:

/**
 * 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 res = 0;
    
    void dfs(TreeNode* root, bool t1, bool t2) {
        if(root == NULL) {
            return;
        }
        if(t2 == true) {
            t2 = false;
            res += root->val;
        }
        if(t1 == true) {
            t1 = false;
            t2 = true;
        }
        if(root->val % 2 == 0) {
            t1 = true;
        }
        dfs(root->left, t1, t2);
        dfs(root->right, t1, t2);
    }

    int sumEvenGrandparent(TreeNode* root) {
        if(root == NULL) {
            return 0;
        }
        if(root->val % 2 == 0) {
            dfs(root->left, true, false);
            dfs(root->right, true, false);
        } else {
            dfs(root->left, false, false);
            dfs(root->right, false, false);
        }

        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_42396397/article/details/106188279
今日推荐