Skip to content

Commit 86179f9

Browse files
authored
Create sum-of-nodes-with-even-valued-grandparent.cpp
1 parent 883a970 commit 86179f9

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Diff for: C++/sum-of-nodes-with-even-valued-grandparent.cpp

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Time: O(n)
2+
// Space: O(h)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
int sumEvenGrandparent(TreeNode* root) {
16+
return sumEvenGrandparentHelper(root, 1, 1);
17+
}
18+
19+
private:
20+
int sumEvenGrandparentHelper(TreeNode *root, int p, int gp) {
21+
return root
22+
? sumEvenGrandparentHelper(root->left, root->val, p) +
23+
sumEvenGrandparentHelper(root->right, root->val, p) +
24+
(gp % 2 == 0 ? root->val : 0)
25+
: 0;
26+
}
27+
};

0 commit comments

Comments
 (0)