File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
17 - Binary Tree Data Structure Problems/16 - Vertical Tree Traversal Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments