您的位置:首页 > 理论基础 > 数据结构算法

SDUT 2137 数据结构实验之求二叉树后序遍历和层次遍历

2012-05-28 19:07 393 查看
题目链接:http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2137

后序遍历没啥好说的,递归就好,层次遍历有点BFS的感觉。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct tree
{
char l;
struct tree *left,*right;
};
struct tree *build(char *p,char *s,int n)
{
struct tree *tail;
int i;
if(n <= 0)return NULL;
tail = (struct tree *)malloc(sizeof(struct tree));
for(i = 0;i <= n-1;i ++)
{
if(p[0] == s[i])
break;
}
tail ->l = p[0];
tail -> left = build (p+1,s,i);
tail -> right = build (p+i+1,s+i+1,n-i-1);
return tail;
}
void downshow(struct tree *k)
{
if(k)
{
downshow(k -> left);
downshow(k -> right);
printf("%c",k -> l);
}
}
void stepshow(struct tree *k,char *p,int n)
{
int i,j,start,end,num;
struct tree *point[1000];
start = 0;
end = 0;
num = 0;
point[0] = k;
while(start < n)
{
j = 1;
for(i = start;i <= end;i ++)
{
p[i] = point[i] -> l;
if(point[i] -> left )
{
point[end + j] = point[i] -> left;
j ++;
}
if(point[i] -> right )
{
point[end + j] = point[i] ->right;
j ++;
}
}
start = end + 1;
end = end + j - 1;
}
p
='\0';
}
int main()
{
char str1[1000],str2[1000],str3[1000];
int t,l;
struct tree *head;
scanf("%d",&t);
while(t--)
{
memset(str3,0,sizeof(str3));
scanf("%s%s",str1,str2);
l = strlen(str1);
head = build(str1,str2,l);
downshow(head);
printf("\n");
stepshow(head,str3,l);
printf("%s\n",str3);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: