-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay91.cpp
More file actions
67 lines (59 loc) · 1.96 KB
/
Day91.cpp
File metadata and controls
67 lines (59 loc) · 1.96 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isEvenOddTree(TreeNode* root) {
if (root == NULL)
return false;
queue<TreeNode*> q;
q.push(root);
int level = -1;
while (!q.empty()) {
level++;
int n = q.size();
int prev = 0;
for (int i = 0; i < n; i++) {
TreeNode* curr = q.front();
q.pop();
if (level == 0 && curr->val % 2 == 0)
return false;
if (i == 0) {
if ((level % 2 == 0 && curr->val % 2 == 1)
|| (level % 2 == 1 && curr->val % 2 == 0)) {
prev = curr->val;
} else {
return false;
}
} else {
if (level % 2 == 1) {
if (curr->val % 2 == 0 && prev > curr->val) {
prev = curr->val;
} else {
return false;
}
} else {
if (curr->val % 2 == 1 && prev < curr->val) {
prev = curr->val;
} else {
return false;
}
}
}
if (curr->left != nullptr)
q.push(curr->left);
if (curr->right != nullptr)
q.push(curr->right);
}
}
return true;
}
};