Vertical print not getting the right output
@guptarahul3100 you have to use level order input and have to input n at the start
corrected code
hope its cleared if yes dont forget to mark the doubt resolved
i am using level order input only i think!!
can u tell me on which line u have change the code except initializing n
Level order input is taken and tree is build by using the queue, in which firstly u will take a queue of nodes, and then it will have a data which will represent a root node, and then u will accept the left and right child of root node, -1 value means that the node does not have any child. @guptarahul3100
i have seen the build function 6 times each and every line of code in the build fuction is same
i dont know what u are seen man.
#include<bits/stdc++.h>
#include
#include
using namespace std ;
class node{
public:
int data ;
node* left ;
node*right ;
node(int d){
data = d ;
left = NULL ;
right = NULL ;
}
} ;
node* build(){
int d ;
cin >> d ;
queue<node*> q ;
node* root = new node(d) ;
q.push(root) ;
int c1,c2 ;
while(!q.empty()){
node*f = q.front() ;
q.pop() ;
cin >> c1 >> c2 ;
if(c1 != -1){
f->left = new node(c1) ;
q.push(f->left) ;
}
if(c2 != -1){
f->right = new node(c1) ;
q.push(f->right) ;
}
}
return root ;
}
void vertical(node*root,int p,map<int,vector> &m){
if(root==NULL) return ;
m[p].push_back(root->data) ;
vertical(root->left,p-1,m) ;
vertical(root->right,p+1,m) ;
return ;
}
int main(){
int n ;
cin >> n ;
node* root = build() ;
map<int,vector> m ;
int p = 0 ;
vertical(root,p,m) ;
for(auto s:m){
for(int l:s.second){
cout << l << " " ;
}
cout << endl ;
}
return 0 ;
}
my code u can see it
@guptarahul3100 at first your code was different it was missing declaration of n and input , also the build function was different
@guptarahul3100 error in your code is
if(c2 != -1){
f->right = new node(c1) ;
q.push(f->right) ;
}
it should be c2 in new node
ok thank you !!!
np just mark it as resolved
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.