Cod sursa(job #2071572)

Utilizator andreeasinAndreea S andreeasin Data 20 noiembrie 2017 19:50:59
Problema Cele mai apropiate puncte din plan Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.15 kb
#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;
}