Skip to content

Commit 3aa0b96

Browse files
authored
Create 2415. Reverse Odd Levels of Binary Tree (#667)
2 parents f538512 + 5ae47f6 commit 3aa0b96

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
};

0 commit comments

Comments
 (0)