blob: e446c0f55b3271f30072169d6c9a94d3c1c68ddc (
plain)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
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) {}
};
#include <queue>
class Solution
{
public:
bool isEvenOddTree(TreeNode *root)
{
if (root == nullptr)
return true;
std::queue<TreeNode *> odd_level;
std::queue<TreeNode *> even_level;
even_level.push(root);
while (true)
{
if (!odd_level.empty())
{
auto node = odd_level.front();
odd_level.pop();
if (node->left)
even_level.push(node->left);
if (node->right)
even_level.push(node->right);
int last = node->val;
if (last % 2 != 0)
return false;
while (!odd_level.empty())
{
node = odd_level.front();
odd_level.pop();
if (node->left)
even_level.push(node->left);
if (node->right)
even_level.push(node->right);
int val = node->val;
if (val % 2 != 0)
return false;
if (val >= last)
return false;
last = val;
}
continue;
}
if (!even_level.empty())
{
auto node = even_level.front();
even_level.pop();
if (node->left)
odd_level.push(node->left);
if (node->right)
odd_level.push(node->right);
int last = node->val;
if (last % 2 == 0)
return false;
while (!even_level.empty())
{
node = even_level.front();
even_level.pop();
if (node->left)
odd_level.push(node->left);
if (node->right)
odd_level.push(node->right);
int val = node->val;
if (val % 2 == 0)
return false;
if (val <= last)
return false;
last = val;
}
continue;
}
break;
}
return true;
}
};
|