0

help me in c++ binary tree i am not able to print tree

input:5 1 L 2 R 3 LL 4 LR 5 NOTE:LL mean left of root->left code: #include <iostream> using namespace std; struct node{ int data; node *left; node *right; }; node* create(int data){ node *temp=new node(); temp->data=data; temp->left=NULL; temp->right=NULL; return temp; } void print(node *root){ if(root=NULL) return; cout<<root->data<<endl; print(root->left); print(root->right); } int main() { int n,r; cin>>n>>r; string s;int a; node* root=create(r); int t=n-1; while(t--) { cin>>s>>a; node *temp=root; for(int i=0;i<s.length();i++){ if(s[i]=='L') { if(temp->left==NULL) temp=create(a); else temp=temp->left; } else { if(temp->right==NULL) temp=create(a); else temp=temp->right; } //cout<<temp->data<<" "; } delete(temp); } print(root); }

11th Aug 2018, 7:14 AM
Bahubali
Bahubali - avatar
6 Réponses
+ 1
It's helpful to other people if you share the code in the playground instead of in question. Easier to read, plus people can test it without retyping the whole thing.
11th Aug 2018, 10:14 AM
Jared Bird
Jared Bird - avatar
+ 1
Is the problem that it will not print, or will not print in order?
11th Aug 2018, 10:17 AM
Jared Bird
Jared Bird - avatar
+ 1
The delete (temp); before the print (root); might cause a problem. Also the logic for adding the nodes doesn't look right. With only one delete this will leak memory, but this will not be stopping you from printing the data. Please put in the code playground.
11th Aug 2018, 11:10 AM
Jared Bird
Jared Bird - avatar
+ 1
IT WORKS:(PROBLEM SOLVED) #include <iostream> using namespace std; struct node{ int data; node *left; node *right; }; node* create(int data){ node *temp=new node(); temp->data=data; temp->left=NULL; temp->right=NULL; return temp; } void print(node *root){ if(root==NULL) return; print(root->left); print(root->right); cout<<root->data<<endl; } int main() { int n,r; cin>>n>>r; string s;int a; node* root=create(r); int t=n-1; node *temp=root; while(t--) { cin>>s>>a; for(int i=0;i<s.length();i++){ if(s[i]=='L') { if((temp)->left==NULL) (temp)->left=create(a); else temp=(temp)->left; } else { if((temp)->right==NULL) (temp)->right =create(a); else temp=(temp)->right; } // cout<<temp->data<<" "; } //delete(temp); } print(root); // cout<<root->data; }
12th Aug 2018, 2:56 AM
Bahubali
Bahubali - avatar
0
there is some error therefore it is not printing the tree
11th Aug 2018, 10:21 AM
Bahubali
Bahubali - avatar
0
i put it in code playground
11th Aug 2018, 11:15 AM
Bahubali
Bahubali - avatar