PAT1099


/*innner order traverse for BST will be ordered
*1.sort the value in buffer
*2.inner traverse the BST and insert the value
*3.be careful for the formatted output
*4.level traverse output using queue
*/


/*c-style code
* abusing in global variable
*not good encapsulation
*may be possible to use reference for 'start'
*/

 #include <cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#define maxn 100
using namespace std;
typedef struct {
int left,right;
int value;
int inserted;
}binode;
binode bitree[maxn];
int buf[maxn];
int start=;
queue<int> q;
void middle_insert(int root)
{
if(root==-)return;
middle_insert(bitree[root].left);
if(bitree[root].left==- || bitree[bitree[root].left].inserted==)
{
bitree[root].value=buf[start];
bitree[root].inserted=;
start++;
//return ;
}
middle_insert(bitree[root].right);
}
void level_traverse()
{
int i=;
q.push();
while(!q.empty())
{
int tmp=q.front();
buf[i++]=bitree[tmp].value;
q.pop();
if(bitree[tmp].left!=-)q.push(bitree[tmp].left);
if(bitree[tmp].right!=-)q.push(bitree[tmp].right);
}
}
int main()
{
//freopen("input.txt","r",stdin);
int i,n;
while(cin>>n)
{
memset(buf,,sizeof(buf));
memset(bitree,,sizeof(bitree));
//fill(bitree,bitree+n,0); parameter must be iterator
for(i=;i<n;i++)scanf(" %d %d",&bitree[i].left,&bitree[i].right);
for(i=;i<n;i++)scanf(" %d",&buf[i]);
sort(buf,buf+n);
//for(i=0;i<n;i++)printf("%d ",buf[i]);
middle_insert();
//for(i=0;i<n;i++)printf("%d %d %d %d\n",i,bitree[i].left,bitree[i].right,bitree[i].value);
level_traverse();
for(i=;i<n;i++){
if(i<n-)printf("%d ",buf[i]);
else printf("%d\n",buf[i]);
}
}
return ;
}

IMPROVE IN  C++

 #include <cstdio>
#include <iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#define maxn 100
using namespace std;
typedef struct {
int left,right;
int value;
int inserted;
}binode; binode bitree[maxn];
int buf[maxn];
void middle_insert(int root,int &start)
{
if(root==-)return;
middle_insert(bitree[root].left,start);
if(bitree[root].left==- || bitree[bitree[root].left].inserted==)
{
bitree[root].value=buf[start];
bitree[root].inserted=;
start++;
//return ;
}
middle_insert(bitree[root].right,start);
}
void level_traverse(binode bitree[],int buf[])
{
queue<int> q;
int i=;
q.push();
while(!q.empty())
{
int tmp=q.front();
buf[i++]=bitree[tmp].value;
q.pop();
if(bitree[tmp].left!=-)q.push(bitree[tmp].left);
if(bitree[tmp].right!=-)q.push(bitree[tmp].right);
}
}
int main()
{ freopen("input.txt","r",stdin);
int n;
while(cin>>n)
{
memset(buf,,sizeof(buf));
memset(bitree,,sizeof(bitree));
for(int i=;i<n;i++)cin>>bitree[i].left>>bitree[i].right;
for(int i=;i<n;i++)cin>>buf[i];
sort(buf,buf+n);
//for(i=0;i<n;i++)printf("%d ",buf[i]);
int start=;
middle_insert(,start);
//for(i=0;i<n;i++)printf("%d %d %d %d\n",i,bitree[i].left,bitree[i].right,bitree[i].value);
level_traverse(bitree,buf);
for(int i=;i<n;i++){
cout<<buf[i];
i==n-?cout<<endl:cout<<' ';
}
}
return ;
}
上一篇:JavaScript的事件对象_鼠标事件


下一篇:django和celery结合应用