LeetCode 1315. 祖父節點值爲偶數的節點和 (遍歷二叉樹)

祖父節點值爲偶數的節點和
由於需要知道祖父節點的值,所以搜索的時候要帶着祖父節點、父親節點、以及當前節點。

/**
 * 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);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章