[Geeks for Geeks] Reverse alternate levels of a perfect binary tree

Reverse alternate levels of a perfect binary tree

Given a complete binary tree, reverse the nodes present at alternate levels.

  • Time : O(n)
  • Space : O(n)
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
void reverseAlternate(Node *root)
{
deque<Node*> dq;
bool reverse = false;
dq.push_back(root);

while(!dq.empty()) {
int sz = dq.size();
if(reverse) {
int l = 0, r = sz - 1;
while(l < r) {
swap(dq[l++]->data, dq[r--]->data);
}
}
while(sz--) {
auto f = dq.front(); dq.pop_front();
if(f->left and f->right) {
dq.push_back(f->left);
dq.push_back(f->right);
}
}

reverse = !reverse;
}
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/reverse-alternate-levels-of-a-perfect-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.