ACwing_1589. 构建二叉搜索树


//
#include<bits/stdc++.h>
using namespace std;
#define T int // T
const int N=111;
T xx[N],yy[N],in[N],ans[N]; // in[N]
int pos;
struct node
{
T data;
node *x,*y;
node( T in=0,node *xx=NULL,node *yy=NULL ):data(in),x(xx),y(yy) {}
};
node* new_tree( int tt,node* &root )
{
if( tt==-1 ) return root; // tt==-1
root=new node( tt );
root->x=new_tree( xx[tt],root->x );
root->y=new_tree( yy[tt],root->y );
return root;
}
void dfs( node *root )
{
if( root==NULL ) return ; // return
dfs( root->x );
root->data=in[pos++];
dfs( root->y );
}
void DD( node *root )
{
if( root==NULL ) return ;
queue<node*> q; node *tt=NULL;
q.push( root );
while( !q.empty() )
{
tt=q.front(); q.pop();
ans[pos++]=tt->data; // tt
if( tt->x ) q.push( tt->x );
if( tt->y ) q.push( tt->y );
}
}
void delete_tree( node *root )
{
if( root==NULL ) return ;
delete_tree( root->x );
delete_tree( root->y );
delete root;
}
int main()
{
int n,i;
while( cin>>n )
{
for( i=0;i<n;i++ ) cin>>xx[i]>>yy[i];
for( i=0;i<n;i++ ) cin>>in[i];
sort( in,in+n ); // sort
node *root=NULL;
new_tree( 0,root );
pos=0; dfs( root );
pos=0; DD( root );
for( i=0;i<pos;i++ )
{
if( i ) cout<<" ";
cout<<ans[i];
}
cout<<endl;
delete_tree( root );
}
return 0;
}
"vs"
01 node *root
root->x=new_tree( root->x );
root->y=new_tree( root->y );
02 node* &root
new_tree( root->x );
new_tree( root->y );