[AlgoExpert] Right Sibling Tree

Right Sibling Tree

  • Time : O(n)
  • Space : O(2^d)
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
#include <vector>
#include <queue>
using namespace std;

// This is the class of the input root. Do not edit it.
class BinaryTree {
public:
int value;
BinaryTree *left = nullptr;
BinaryTree *right = nullptr;

BinaryTree(int value);
};

BinaryTree *rightSiblingTree(BinaryTree *root) {
queue<BinaryTree*> q;
q.push(root);
while(true) {
bool pushed = false;
int sz = q.size();
while(sz--) {
auto node = q.front(); q.pop();
if(node == nullptr) {
q.push(nullptr);
} else {
if(!node->left and !node->right) q.push(nullptr);
else {
q.push(node->left); q.push(node->right);
pushed = true;
}
node->right = nullptr;
if(sz) node->right = q.front();
}
}
if(!pushed) break;
}
return root;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/right-sibling-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.