Can someone plz help i have done this problem in C++ 14 its working fine on compiler but while submittng its showing wrong
created
last reply
- 3
replies
- 598
views
- 2
users
- 1
like
Can someone plz help i have done this problem in C++ 14 its working fine on compiler but while submittng its showing wrong
You do realise the example test case given in the problem is just that - a small sample to clarify the problem and illustrate the I/O format. Your program will also be tested against hidden test cases that are likely to test the full range of the data.
If you want us to help, you’ll need to post your code here. Please put three back-ticks ``` on a line by themselves both before and after the code so that it isn’t interpreted by the editor.
using namespace std;
template<typename T>
class Binarytree{
public:
T data;
Binarytree<T> *left;
Binarytree<T> *right;
Binarytree(T data){
this->data=data;
left=NULL;
right=NULL;
}
~Binarytree(){
if (left) delete left;
if (right) delete right;
}
};
void preorder(Binarytree<int>* root)
{
if(root==NULL)
{
return;
}
cout<<" "<<root->data;
preorder(root->left);
preorder(root->right);
}
void postorder(Binarytree<int>* root){
if(root==NULL)
return;
postorder(root->left);
postorder(root->right);
cout<<" "<<root->data;
}
Binarytree<int>* construct(int *arr,int si,int end)
{
if(si>end)
{
return NULL;
}
int mid=(si+end)/2;
Binarytree<int>* root=new Binarytree<int>(arr[mid]);
Binarytree<int>*lchild=construct(arr,si,mid-1);
Binarytree<int>* rchild=construct(arr,mid+1,end);
root->left=lchild;
root->right=rchild;
return root;
}
int main() {
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
sort(arr,arr+n);
Binarytree<int>* root=construct(arr,0,n-1);
cout<<"Pre order :";
preorder(root);
cout<<"\n";
cout<<"In order :";
for(int i=0;i<n;i++)
{
cout<<" "<<arr[i];
}cout<<"\n";
cout<<"Post order:";
postorder(root);
cout<<endl;
delete root;
cout<<endl;
return 0;
}```
I don’t think you should be sorting the input. You should read each value and add it to the tree in turn. Compare it to the current node, and add it to the left subtree if smaller than the current value, else add it to the right subtree.
For example, this input:
10
10 23 546 233 65 73 45 2 5 7
should give this output:
Pre order : 10 2 5 7 23 546 233 65 45 73
In order : 2 5 7 10 23 45 65 73 233 546
Post order: 7 5 2 45 73 65 233 546 23 10
Topic | Category | Replies | Views | Activity |
---|---|---|---|---|
Getting WA on the problem PIE continuously, what am I missing? spoj.com | ProblemSet Archive | 2 | 178 | Mar 8 |
Getting TLE in AKBAR - Akbar , The great. Why? | ProblemSet Archive | 3 | 190 | Mar 11 |
COT - Count on a tree - TLE | ProblemSet Archive | 1 | 131 | Mar 18 |
AIBOHPHOBIA - LPS vs Direct Approach | ProblemSet Archive | 1 | 113 | Mar 31 |
Beangame | ProblemSet Archive | 2 | 124 | Apr 9 |