美文网首页
1315. Sum of Nodes with Even-Val

1315. Sum of Nodes with Even-Val

作者: 是嘤嘤嘤呀 | 来源:发表于2020-03-30 14:33 被阅读0次
image.png

思路:先序遍历
代码片段

/**
 * 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 sumEvenGrandparent(TreeNode* root) {
        int res = 0;
        if (root) {
            if (root -> val % 2 == 0) {
                if (root -> left) {
                    if (root -> left -> left) {
                        res += root -> left -> left -> val;
                    }
                    if (root -> left -> right) {
                        res += root -> left -> right -> val;
                    }
                }
                if (root -> right) {
                    if (root -> right -> left) {
                        res += root -> right -> left -> val;
                    }
                    if (root -> right -> right) {
                        res += root -> right -> right -> val;
                    }
                }
            }
            if (root -> left) res += sumEvenGrandparent(root -> left);
            if (root -> right) res += sumEvenGrandparent(root -> right);
        }
        return res;
    }
};

相关文章

网友评论

      本文标题:1315. Sum of Nodes with Even-Val

      本文链接:https://www.haomeiwen.com/subject/vrlvuhtx.html