机试指南 3.3二叉树
例3.4二叉树遍历
#include<stdio.h>
#include<string.h>
struct node{
node *lchild;
node *rchild;
char c;
}tree[50];
int loc;
char str1[30];
char str2[30];
node *create();
void postOrder(node *t);
node *build(int s1,int e1,int s2,int e2);
int main()
{
while(scanf("%s",str1)!=EOF)
{
scanf("%s",str2);
int l1=strlen(str1);
int l2=strlen(str2);
loc=0;
node *T=build(0,l1-1,0,l2-1);
postOrder(T);
printf("\n");
}
return 0;
}
node *create()
{
tree[loc].lchild=NULL;
tree[loc].rchild=NULL;
return &tree[loc++];
}
void postOrder(node *t)
{
if(t->lchild!=NULL)
postOrder(t->lchild);
if(t->rchild!=NULL)
postOrder(t->rchild);
printf("%c",t->c);
}
node *build(int s1,int e1,int s2,int e2)
{
node *ret=create();
ret->c=str1[s1];
int idx;
for(int i=s2;i<=e2;i++)
{
if(str2[i]==ret->c)
{
idx=i;
break;
}
}
if(idx!=s2)
ret->lchild=build(s1+1,s1+(idx-s2),s2,idx-1);
if(idx!=e2)
ret->rchild=build(s1+(idx-s2)+1,e1,idx+1,e2);
return ret;
}
练1:二叉树KY85
#include<stdio.h>
int countx(int t,int n)
{
if(t<=n)
{
if( (t*2<=n) && ((t*2+1)<=n) )
return 1+countx(t*2,n)+countx(t*2+1,n);
else if( (t*2<=n) && ((t*2+1)>n) )
return 1+countx(t*2,n);
else if(t*2>n)
return 1;
}
else
return 0;
}
int main()
{
int m,n;
while(scanf("%d%d",&m,&n)!=EOF)
{
if(m==0&&n==0)
break;
int result;
result=countx(m,n);
printf("%d\n",result);
}
return 0;
}
练1:二叉树KY47
#include<stdio.h>
#include<math.h>
int degree(int t)
{
int d=1;
while(true)
{
if(pow(2,d-1)>t)
break;
d++;
}
return --d;
}
int main()
{
int x,y;
while(scanf("%d%d",&x,&y)!=EOF)
{
if(x==y)
{
printf("%d\n",x);
continue;
}
if(degree(x)>degree(y))
{
int z=x;
x=y;
y=z;
}
if(degree(x)<degree(y))
{
int a=degree(y)-degree(x);
for(int i=0;i<a;i++)
y=y/2;
}
while(true)
{
if(x==y)
break;
x=x/2;
y=y/2;
}
printf("%d\n",x);
}
return 0;
}
练2:树查找
#include<stdio.h>
#include<math.h>
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int buf[1000];
for(int i=1;i<=n;i++)
scanf("%d",&buf[i]);
int count;
scanf("%d",&count);
if(pow(2,count-1)<=n)
{
int x=pow(2,count-1);
printf("%d",buf[x]);
while(true)
{
x++;
if(x>=pow(2,count))
break;
printf(" %d",buf[x]);
}
printf("\n");
}
else
printf("EMPTY\n");
}
return 0;
}