File tree Expand file tree Collapse file tree
contest/leetcode_biweek_17_problems Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 {
1016class Solution {
1117public:
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};
You can’t perform that action at this time.
0 commit comments