Skip to content

Commit 4d6ebbc

Browse files
committed
added required changes to vertical order traversal
1 parent 54ed83e commit 4d6ebbc

File tree

1 file changed

+77
-3
lines changed

1 file changed

+77
-3
lines changed

Tree/Traverals/CPP/vertical order traversal.cpp

+77-3
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,12 @@
44
/*---video tutorial of approach used---*/
55
// link: https://www.youtube.com/watch?v=4w2Ri4VhgZo&list=PLjhq5EHRYAeLdh0xtn2v7wbQsVc8WAB2e&index=6&ab_channel=CodeCampaign
66

7+
#include<bits/stdc++.h>
8+
#include<sstream>
9+
using namespace std;
10+
711
/*----STRUCTURE OF TREE NODE-----*/
8-
/*
12+
913
class TreeNode{
1014
public:
1115
int val;
@@ -18,7 +22,56 @@ class TreeNode{
1822
this->right=NULL;
1923
}
2024
};
21-
*/
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+
2275

2376
/*-------- FUNCTION FOR VERTICAL ORDER TRAVERSAL---------*/
2477

@@ -31,6 +84,8 @@ void PrintVerticalOrder(TreeNode* root, int d, map<int, vector<int> > &m){
3184
PrintVerticalOrder(root->right,d+1,m);
3285
}
3386

87+
// Driver Code
88+
3489
int main(){
3590
// fast I/O
3691
ios_base::sync_with_stdio(false);
@@ -53,4 +108,23 @@ int main(){
53108

54109

55110
return 0;
56-
}
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

Comments
 (0)