ORIGIN

LeetCode 1315. Sum of Nodes with Even-Valued Grandparent

ACM 1 mins224 words

Problem Description

1315. Sum of Nodes with Even-Valued Grandparent

Analysis

This is a normal tree traverse by layer problem.

But in DFS, we can not directly find its grandson or grandparent. So we can use the parent to represent grandparent.

1
queue<pair<TreeNode*, bool>> que;

The second element of pair represents the status of it’s parent node status.

if the second element is true, then it means its parent is an even node, so we add its son node value into the sum if it has left or right child.

And to start, the root node has no parent so its parent status should be false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
int sumEvenGrandparent(TreeNode* root) {
if(root == nullptr) return 0;
queue<pair<TreeNode*, bool>> que;
que.push(make_pair(root, false));
int sum = 0;
while(!que.empty()) {
auto t = que.front();
que.pop();
int isEven = false;
if(t.first->val % 2 == 0) isEven = true;
if(t.first->left) {
if(t.second == true) {
sum += t.first->left->val;
}
que.push(make_pair(t.first->left, isEven));
}
if(t.first->right) {
if(t.second == true) {
sum += t.first->right->val;
}
que.push(make_pair(t.first->right, isEven));
}
}
return sum;
}
};
TOP
COMMENT
  • ABOUT
  • |
o_oyao
  The Jigsaw puzzle is incomplete with even one missing piece. And I want to be the last piece to make the puzzle complete.
Like my post?
Default QR Code
made with ❤️ by o_oyao
©o_oyao 2019-2024

|