呃,我知道要用DFS,但乍看題目看不懂什麼是even-value的意思,所以只好看Hint跟Discussion
二元樹中,如果現在節點的上上層節點的值是偶數,就把現在節點的值sum起來
class Solution {
public:
int sumEvenGrandparent(TreeNode* root) {
return sum(root, NULL, NULL); // root沒父沒祖母
}
private:
int sum(TreeNode* curr_node, TreeNode* parent, TreeNode* grandParent) {
if (curr_node == NULL) {
return 0;
}
int addition = 0;
if (grandParent != NULL)
addition = curr_node->val;
TreeNode* Im_even_node= NULL;
if (curr_node->val % 2 == 0)
Im_even_node = curr_node;
return addition + sum(curr_node->left, Im_even_node, parent) + sum(curr_node->right, Im_even_node, parent);
}
};