-
Notifications
You must be signed in to change notification settings - Fork 0
/
sibling.cpp
106 lines (99 loc) · 2.06 KB
/
sibling.cpp
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include<iostream>
#include<climits>
#include<vector>
#include<queue>
using namespace std;
class Node{
public:
int data;
Node * left;
Node * right;
Node * nextRight;
Node(int val): data(val),left(NULL), right(NULL), nextRight(NULL){};
Node (): data(0), left(NULL), right(NULL), nextRight(NULL){};
};
void buildTree(int * arr, int size, Node * nodeArr){
for(int i=0; i<size; i++){
if(arr[i]!=0){
if(i==0){
nodeArr[0].data= arr[i];
}
else{
nodeArr[i].data = arr[i];
int parentPos= (i-1)/2;
//Node parent = nodeArr[parentPos];
if(i%2 == 1)
nodeArr[parentPos].left=&nodeArr[i];
else
nodeArr[parentPos].right=&nodeArr[i];
}
}
}
return ;
}
vector <Node *> siblings;
bool nodeIsLeaf( Node * node){
if(( node->left == NULL) && (node->right== NULL))
return true;
else
return false;
}
void connectSibling(Node * n){
if(nodeIsLeaf(n)){
if(siblings.empty())
siblings.push_back(n);
else{
siblings[siblings.size()-1]->nextRight=n;
siblings.push_back(n);
}
}
return;
}
void buildSiblingP(Node *node){
if(node == NULL) return;
buildSiblingP(node->left);
connectSibling(node);
buildSiblingP(node->right);
}
void set_sibling_pointer(Node *root){
Node *slow,*fast;
slow=fast=root;
while(slow != NULL){
if(slow->left){
fast->nextRight=slow->left;
fast=fast->nextRight;
}
if(slow->right){
fast->nextRight=slow->right;
fast=fast->nextRight;
}
slow=slow->nextRight;
}
}
int main(){
int n;
int num;
cin>> n;
int inputArr[n];
for (int i =0; i<n; i++){
cin>> num;
inputArr[i]=num;
}
Node root[n];
buildTree(inputArr, n, root);
buildSiblingP(root);
Node * current = siblings[0];
cout << endl;
while(current){
cout << current->data << " ";
current = current->nextRight;
}
set_sibling_pointer(root);
cout << endl;
Node * curr = root;
while(curr){
cout << curr->data << " ";
curr = curr->nextRight;
}
return 0;
}