-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBT.cpp
More file actions
90 lines (73 loc) · 1.47 KB
/
BT.cpp
File metadata and controls
90 lines (73 loc) · 1.47 KB
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
#include<queue>
#include<map>
#include<iterator>
#include<vector>
#include<iostream>
#include<set>
using namespace std;
struct BTNode
{
int data;
BTNode *left;
BTNode *right;
};
BTNode* BTNew(int key)
{
BTNode* temp = new BTNode ;
temp->data = key;
temp->left = temp->right = NULL;
return temp;
};
void verticalOrder( BTNode* root);
int main()
{
struct BTNode *root = BTNew(15);
root->left = BTNew(9);
root->left->left = BTNew(20);
root->right= BTNew(20);
root->right->left = BTNew(3);
root->right->right = BTNew(7);
verticalOrder(root);
}
void verticalOrder( BTNode* root)
{
if(!root)
exit(1);
map<int, vector<int> > ord;
int hd=0, node;
queue<pair<BTNode*, int> > q;
q.push(make_pair(root,hd));
while(!q.empty())
{
map<int,set<int> > t;
for(int i=0; i<q.size(); i++)
{
auto temp = q.front();
q.pop();
t[temp.second].insert(temp.first->data);
if(temp.first->left)
q.push(make_pair(temp.first->left, temp.second-1));
if(temp.first->right)
q.push(make_pair(temp.first->right, temp.second+1));
}
for(auto x:t)
{
for(auto d:x.second)
{
ord[x.first].push_back(d);
}
}
}
vector<vector<int> > v;
for(auto it :ord)
{
sort(it.second.begin(),it.second.end());
v.push_back(it.second);
}
for (int i = 0; i < v.size(); i++)
{
for (int j = 0; j < v[i].size(); j++)
cout << v[i][j] << " ";
cout << endl;
}
}