//
#include<bits/stdc++.h>
using namespace std;
#define T int // 随时修改数据类型
const int N=111;
T ans[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) {}
};
void new_tree( int n,node* &root )
{
while( n-- )
{
T data; cin>>data;
node *tt=new node( data );
if( root==NULL ) { root=tt; continue; }
node *rp=root; // 移动指针
while( 1 )
{
if( data < rp->data ) // left
{
if( rp->x ) rp=rp->x;
else { rp->x=tt; break; }
}
else // right
{
if( rp->y ) rp=rp->y;
else { rp->y=tt; break; }
}
}
}
}
void BB( node *root )
{
if( root==NULL ) return ;
BB( root->x );
ans[pos++]=root->data;
BB( root->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 )
{
node *root=NULL;
new_tree( n,root );
pos=0; BB( root );
for( i=0;i<pos;i++ )
{
if( i ) cout<<" ";
cout<<ans[i];
}
cout<<endl;
delete_tree( root );
}
return 0;
}
模板_建立二叉搜索树_递推
猜你喜欢
转载自blog.csdn.net/qq_63173957/article/details/125022412
今日推荐
周排行