File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ bool isEvenOddTree(TreeNode* root) {
4+ if (root == nullptr)
5+ return false;
6+
7+ queue<TreeNode*> q;
8+ q.push(root);
9+ int level = -1;
10+
11+ while (!q.empty()) {
12+ level++;
13+ int size = q.size();
14+ int prev = 0;
15+
16+ for (int i = 0; i < size; i++) {
17+ TreeNode* curr = q.front();
18+ q.pop();
19+
20+ if (level == 0 && curr->val % 2 == 0)
21+ return false;
22+
23+ if (i == 0) {
24+ if ((level % 2 == 0 && curr->val % 2 == 1)
25+ || (level % 2 == 1 && curr->val % 2 == 0)) {
26+ prev = curr->val;
27+ } else {
28+ return false;
29+ }
30+ } else {
31+ if (level % 2 == 1) {
32+ if (curr->val % 2 == 0 && prev > curr->val) {
33+ prev = curr->val;
34+ } else {
35+ return false;
36+ }
37+ } else {
38+ if (curr->val % 2 == 1 && prev < curr->val) {
39+ prev = curr->val;
40+ } else {
41+ return false;
42+ }
43+ }
44+ }
45+
46+ if (curr->left != nullptr)
47+ q.push(curr->left);
48+
49+ if (curr->right != nullptr)
50+ q.push(curr->right);
51+ }
52+ }
53+
54+ return true;
55+ }
56+ };
You can’t perform that action at this time.
0 commit comments