forked from garvit-bhardwaj/Leetcode-Problems-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Even_Odd_Tree
82 lines (78 loc) · 2.04 KB
/
Even_Odd_Tree
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
class Solution {
public:
bool isEvenOddTree(TreeNode* root) {
if(root->val%2==0)
return 0;
queue<TreeNode*>q;
q.push(root);
int level=0;
int ok=1;
while(q.empty()!=1)
{
vector<int>arr;
int s=q.size();
for(int i=0;i<s;i++)
{
TreeNode*tmp=q.front();
q.pop();
arr.push_back(tmp->val);
if(tmp->left)
q.push(tmp->left);
if(tmp->right)
q.push(tmp->right);
}
// for(auto i:arr)
// {
// cout<<i<<" ";
// }
// cout<<"\n";
if(level%2==0)
{
int i=0;
while(i+1<arr.size() && arr[i]<arr[i+1] && arr[i]%2==1 && arr[i+1]%2==1)
{
i++;
}
if(arr.size()==1)
{
if(arr[0]%2==0)
{
ok=0;
break;
}
}
else if(i!=arr.size()-1)
{
ok=0;
break;
}
}
else{
// cout<<"FDf\n";
///cout<<level<<"\n";
int i=0;
while(i+1<arr.size() && arr[i]>arr[i+1] && arr[i]%2==0 && arr[i+1]%2==0)
{
i++;
}
//cout<<"Gf\n";
// cout<<i<<"\n";
if(arr.size()==1)
{
if(arr[0]%2!=0)
{
ok=0;
break;
}
}
else if(i!=arr.size()-1)
{
ok=0;
break;
}
}
level++;
}
return ok;
}
};