Pagini recente » Cod sursa (job #1885067) | Statistici Cristina Opriceana (cristina2689) | Rating Gheorghe Ion (ertyu) | Cod sursa (job #1357527) | Cod sursa (job #2071572)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream f("date.in.txt");
ofstream g("date.out.txt");
struct nod
{
int data;
nod *stg,*dr;
};
nod* newNode(int nr)
{
nod *aux=new nod;
aux->stg=aux->dr=NULL;
aux->data=nr;
return aux;
}
void preOrdine(nod *root)
{
if(root)
{
g<<root->data<<" ";
preOrdine(root->stg);
preOrdine(root->dr);
}
}
void inOrdine(nod *root)
{
if(root)
{
inOrdine(root->stg);
g<<root->data<<" ";
inOrdine(root->dr);
}
}
void postOrdine(nod *root)
{
if(root)
{
postOrdine(root->stg);
postOrdine(root->dr);
g<<root->data<<" ";
}
}
nod* Build_Tree(vector<int> &inord, vector<int> &postord,vector <int> &poz, int inordStart, int inordEnd, int &pIndex, bool &valid)
{
if(!valid)
return NULL;
if(inordStart>inordEnd)
return NULL;
nod *node=newNode(postord[pIndex]);
pIndex--;
if(inordStart==inordEnd)
return node;
int index=poz[node->data];
if(index>=inordStart && index<=inordEnd)
{
node->dr=Build_Tree(inord,postord,poz,index+1,inordEnd,pIndex,valid);
node->stg=Build_Tree(inord,postord,poz,inordStart,index-1,pIndex,valid);
return node;
}
else
{
valid=0;
return NULL;
}
}
void checkTree(nod* root, int& nr, int n)
{
if(root)
{
nr++;
checkTree(root->stg,nr,n);
checkTree(root->dr,nr,n);
}
}
int main()
{
int n,i,x,pIndex,nr=0;
vector<int> inord,postord;
bool valid=1;
nod *root;
f>>n;
vector<int> poz(n,0);
for(i=0;i<n;i++)
{
f>>x;
postord.push_back(x);
}
for(i=0;i<n;i++)
{
f>>x;
inord.push_back(x);
poz[x]=i;
}
pIndex=n-1;
root=Build_Tree(inord,postord,poz,0,n-1,pIndex,valid);
if(valid)
{
preOrdine(root);
g<<endl;
inOrdine(root);
g<<endl;
postOrdine(root);
}
else g<<"nu";
return 0;
}