Skip to content

Commit 60367ae

Browse files
committed
[not completed]leetcode contest biweekly 17
1 parent a923592 commit 60367ae

1 file changed

Lines changed: 33 additions & 1 deletion

File tree

contest/leetcode_biweek_17_problems/leetcode_5145_Sum_of_Nodes_with_Even-Valued_Grandparent.cpp

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
/**
2+
* AC:
3+
* 思路:递归,定义 f(node), 对于每一个 node,判断到孙子节点,如果当前 node->val 为偶,
4+
* 则加进其孙子节点的值(如果存在),然后 再递归累加 ret += f(node->left) + f(node->right)
5+
* T:O(n), n 为二叉树的节点数
6+
*/
17
/**
28
* Definition for a binary tree node.
39
* struct TreeNode {
@@ -10,6 +16,32 @@
1016
class Solution {
1117
public:
1218
int sumEvenGrandparent(TreeNode* root) {
13-
19+
TreeNode* tmp = root;
20+
int ret = 0;
21+
if(root->val % 2 == 0) { // 偶数点
22+
if(root->left) {
23+
if(root->left->left)
24+
ret += root->left->left->val;
25+
if(root->left->right)
26+
ret += root->left->right->val;
27+
ret += sumEvenGrandparent(root->left); // 递归
28+
}
29+
if(root->right) {
30+
if(root->right->left)
31+
ret += root->right->left->val;
32+
if(root->right->right)
33+
ret += root->right->right->val;
34+
ret += sumEvenGrandparent(root->right);
35+
}
36+
} else {
37+
if(root->left) {
38+
ret += sumEvenGrandparent(root->left); // 递归
39+
}
40+
if(root->right) {
41+
ret += sumEvenGrandparent(root->right);
42+
}
43+
}
44+
45+
return ret;
1446
}
1547
};

0 commit comments

Comments
 (0)