1
+ /* ---Problem Description---*/
2
+ // problem description can be found at: https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/
3
+
4
+ /* ---video tutorial of approach used---*/
5
+ // link: https://www.youtube.com/watch?v=4w2Ri4VhgZo&list=PLjhq5EHRYAeLdh0xtn2v7wbQsVc8WAB2e&index=6&ab_channel=CodeCampaign
6
+
7
+ #include < bits/stdc++.h>
8
+ #include < sstream>
9
+ using namespace std ;
10
+
11
+ /* ----STRUCTURE OF TREE NODE-----*/
12
+
13
+ class TreeNode {
14
+ public:
15
+ int val;
16
+ TreeNode* left;
17
+ TreeNode* right;
18
+
19
+ TreeNode (int data){
20
+ this ->val =data;
21
+ this ->left =NULL ;
22
+ this ->right =NULL ;
23
+ }
24
+ };
25
+
26
+
27
+ // Function to Build Tree
28
+
29
+ TreeNode* Buildtree ()
30
+ {
31
+ int a;
32
+ cin >> a;
33
+ TreeNode *root = new TreeNode (a);
34
+ queue<TreeNode*> q;
35
+ q.push (root);
36
+ while (!q.empty ())
37
+ {
38
+ cin >> a;
39
+ if (a != -1 )
40
+ {
41
+ TreeNode *temp = new TreeNode (a);
42
+ if (q.front ()->left == NULL ){
43
+ q.front ()->left = temp;
44
+ }
45
+ else
46
+ {
47
+ q.front ()->right = temp;
48
+ q.pop ();
49
+ }
50
+ q.push (temp);
51
+ }
52
+ else
53
+ {
54
+ if (q.front ()->left == NULL )
55
+ {
56
+ cin >> a;
57
+ if (a == -1 ){
58
+ q.pop ();
59
+ }
60
+ else {
61
+ TreeNode *temp1 = new TreeNode (a);
62
+ q.front ()->right = temp1;
63
+ q.pop ();
64
+ q.push (temp1);
65
+ }
66
+ }
67
+ else {
68
+ q.pop ();
69
+ }
70
+ }
71
+ }
72
+ return root;
73
+ }
74
+
75
+
76
+ /* -------- FUNCTION FOR VERTICAL ORDER TRAVERSAL---------*/
77
+
78
+ void PrintVerticalOrder (TreeNode* root, int d, map<int , vector<int > > &m){
79
+ if (root==NULL ){
80
+ return ;
81
+ }
82
+ m[d].push_back (root->val );
83
+ PrintVerticalOrder (root->left ,d-1 ,m);
84
+ PrintVerticalOrder (root->right ,d+1 ,m);
85
+ }
86
+
87
+ // Driver Code
88
+
89
+ int main (){
90
+ // fast I/O
91
+ ios_base::sync_with_stdio (false );
92
+ cin.tie (NULL );
93
+
94
+ // Buildtree is function to build tree (as per input or your convienience, you can define it)
95
+ TreeNode* root=Buildtree ();
96
+
97
+
98
+ map<int ,vector<int > > m;
99
+ PrintVerticalOrder (root,0 ,m);
100
+
101
+ // printing the vertical order traversal
102
+ for (auto p:m){
103
+ for (auto x:p.second ){
104
+ cout<<x<<" " ;
105
+ }
106
+ cout<<endl;
107
+ }
108
+
109
+
110
+ return 0 ;
111
+ }
112
+
113
+ /* ---- SAMPLE INPUT/OUTPUT FOR A TREE ----*/
114
+ /*
115
+ input : 1 2 3 4 5 6 -1 -1 -1 -1 -1 -1 -1
116
+ tree corresponding to the input:
117
+
118
+ 1
119
+ / \
120
+ 2 3
121
+ / \ /
122
+ 4 5 6
123
+
124
+ output:
125
+ 4
126
+ 2
127
+ 1 5 6
128
+ 3
129
+ this is the vertical order traversal of a tree
130
+ */
0 commit comments