HDU_1710 Binary Tree Traversals_二叉树

//
#include<bits/stdc++.h>
using namespace std;

const int N=1111;
int a[N],b[N],c[N],d[N],ans[N];
int pos;

struct node
{
    int data;
    node *x,*y;
    node( int in=0,node* xx=NULL,node* yy=NULL ):data(in),x(xx),y(yy) {}
};

void new_tree( int x,int y,int &root_pos,node* &root )
{
    int i,f=-1;
    for( i=x;i<=y;i++ )
        if( a[root_pos]==b[i] )
        {
            f=i; break;
        }
    if( f==-1 ) return ;
    
    root=new node( b[f] ); root_pos++;
    new_tree( x,f-1,root_pos,root->x );
    new_tree( f+1,y,root_pos,root->y );
}

void CC( node *root )
{
    if( root==NULL ) return ;
    CC( root->x );
    CC( root->y );
    ans[pos++]=root->data;
}

void delete_tree( node *root )
{
    if( root==NULL ) return ;
    delete_tree( root->x );
    delete_tree( root->y );
    delete root;
}

int main()
{
    int n,i,nn;
    while( cin>>n )
    {
        node *root=NULL;
        for( i=1;i<=n;i++ ) cin>>a[i];
        for( i=1;i<=n;i++ ) cin>>b[i];
        nn=1;
        new_tree( 1,n,nn,root );
        pos=0; CC( root );
        for( i=0;i<n;i++ )
        {
            if( i ) cout<<" ";
            cout<<ans[i];
        }
        cout<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_63173957/article/details/124576929