File tree 1 file changed +46
-0
lines changed
1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ TreeNode* reverseOddLevels(TreeNode* root) {
4
+ // we are given a perfect binary tree;
5
+ vector<TreeNode*> prev;
6
+ vector<TreeNode*> next;
7
+ queue<TreeNode*> q;
8
+ next.push_back(root);
9
+ q.push(root);
10
+ int lvl = 0;
11
+ while(next.empty() == false) {
12
+ // for(TreeNode* i : prev) cout<<i->val<<" ";
13
+ // cout<<endl;
14
+ // for(TreeNode* i : next) cout<<i->val<<" ";
15
+ // cout<<endl;
16
+ int index = 0;
17
+ if (lvl & 1)
18
+ reverse(next.begin(),next.end());
19
+
20
+ for(TreeNode* i:prev) {
21
+ i->left = next[index];
22
+ i->right = next[index + 1];
23
+ index += 2;
24
+ }
25
+
26
+ lvl+=1;
27
+ prev = next;
28
+ vector<TreeNode*> temp;
29
+ int q_size = q.size();
30
+ while(q_size--) {
31
+ TreeNode* front = q.front();
32
+ q.pop();
33
+ if (front -> left != NULL) {
34
+ temp.push_back(front->left);
35
+ q.push(front->left);
36
+ }
37
+ if (front -> right != NULL) {
38
+ temp.push_back(front->right);
39
+ q.push(front->right);
40
+ }
41
+ }
42
+ next = temp;
43
+ }
44
+ return root;
45
+ }
46
+ };
You can’t perform that action at this time.
0 commit comments