LeetCode 1315. 祖父节点值为偶数的节点和 (遍历二叉树)

    技术2022-07-10  131

    祖父节点值为偶数的节点和 由于需要知道祖父节点的值,所以搜索的时候要带着祖父节点、父亲节点、以及当前节点。

    /** * 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 ans=0; int sumEvenGrandparent(TreeNode* root) { dfs(nullptr,nullptr,root); return ans; } void dfs(TreeNode* gp,TreeNode* par,TreeNode* cur){ if(!cur) return; if(gp && gp->val % 2==0){ ans+=cur->val; } dfs(par,cur,cur->left); dfs(par,cur,cur->right); } };
    Processed: 0.011, SQL: 9