-
Notifications
You must be signed in to change notification settings - Fork 0
/
Construct Binary Tree from Parent Array.cpp
135 lines (107 loc) · 2.51 KB
/
Construct Binary Tree from Parent Array.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* left;
struct Node* right;
Node(int x) {
data = x;
left = right = NULL;
}
};
void sort_and_print(vector<int>& v) {
sort(v.begin(), v.end());
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
v.clear();
}
void printLevelOrder(struct Node* root) {
vector<int> v;
queue<Node*> q;
q.push(root);
Node* next_row = NULL;
while (!q.empty()) {
Node* n = q.front();
q.pop();
if (n == next_row) {
sort_and_print(v);
next_row = NULL;
}
v.push_back(n->data);
if (n->left) {
q.push(n->left);
if (next_row == NULL)
next_row = n->left;
}
if (n->right) {
q.push(n->right);
if (next_row == NULL)
next_row = n->right;
}
}
sort_and_print(v);
}
Node* createTree(int parent[], int n);
/* Driver program to test above function*/
// } Driver Code Ends
/* node structure used in the program
struct Node
{
int data;
struct Node* left;
struct Node* right;
Node(int x){
data = x;
left = right = NULL;
}
}; */
class Solution {
public:
// Function to construct binary tree from parent array.
Node *createTree(vector<int> parent) {
// Your code here
unordered_map<int, Node*> mapping;
Node* root = nullptr;
for (int i = 0; i < parent.size(); ++i) {
if (mapping.find(i) == mapping.end()) {
mapping[i] = new Node(i);
}
if (parent[i] == -1) {
root = mapping[i];
} else {
if (mapping.find(parent[i]) == mapping.end()) {
mapping[parent[i]] = new Node(parent[i]);
}
Node* parentNode = mapping[parent[i]];
if (parentNode->left == nullptr) {
parentNode->left = mapping[i];
} else {
parentNode->right = mapping[i];
}
}
}
return root;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
a.push_back(x);
}
Solution ob;
Node* res = ob.createTree(a);
printLevelOrder(res);
cout << endl;
}
return 0;
}
// } Driver Code Ends