Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions 2415. Reverse Odd Levels of Binary Tree
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
class Solution {
public:
TreeNode* reverseOddLevels(TreeNode* root) {
// we are given a perfect binary tree;
vector<TreeNode*> prev;
vector<TreeNode*> next;
queue<TreeNode*> q;
next.push_back(root);
q.push(root);
int lvl = 0;
while(next.empty() == false) {
// for(TreeNode* i : prev) cout<<i->val<<" ";
// cout<<endl;
// for(TreeNode* i : next) cout<<i->val<<" ";
// cout<<endl;
int index = 0;
if (lvl & 1)
reverse(next.begin(),next.end());

for(TreeNode* i:prev) {
i->left = next[index];
i->right = next[index + 1];
index += 2;
}

lvl+=1;
prev = next;
vector<TreeNode*> temp;
int q_size = q.size();
while(q_size--) {
TreeNode* front = q.front();
q.pop();
if (front -> left != NULL) {
temp.push_back(front->left);
q.push(front->left);
}
if (front -> right != NULL) {
temp.push_back(front->right);
q.push(front->right);
}
}
next = temp;
}
return root;
}
};
Loading