Skip to content

Commit bd9206a

Browse files
authored
Create main.cpp
1 parent 02453bc commit bd9206a

File tree

1 file changed

+42
-0
lines changed
  • 17 - Binary Tree Data Structure Problems/16 - Vertical Tree Traversal

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution
2+
{
3+
public:
4+
//Function to find the vertical order traversal of Binary Tree.
5+
vector<int> verticalOrder(Node *root)
6+
{
7+
map<int, map<int, vector<int> >> nodes;
8+
queue<pair<Node*, pair<int, int> >> q;
9+
10+
vector<int> ans;
11+
if(root == NULL) return ans;
12+
13+
q.push(make_pair(root, make_pair(0, 0)));
14+
15+
while(!q.empty()){
16+
pair<Node*, pair<int, int> > temp = q.front();
17+
q.pop();
18+
Node* frontNode = temp.first;
19+
int hd = temp.second.first;
20+
int lvl = temp.second.second;
21+
22+
nodes[hd][lvl].push_back(frontNode -> data);
23+
24+
if(frontNode -> left)
25+
q.push(make_pair(frontNode -> left, make_pair(hd -1 , lvl + 1)));
26+
27+
if(frontNode -> right)
28+
q.push(make_pair(frontNode -> right, make_pair(hd + 1, lvl + 1)));
29+
}
30+
31+
for(auto i : nodes){
32+
for(auto j : i.second){
33+
for(auto k : j.second){
34+
ans.push_back(k);
35+
}
36+
}
37+
}
38+
39+
40+
return ans;
41+
}
42+
};

0 commit comments

Comments
 (0)