版权声明:博主瞎写,随便看看 https://blog.csdn.net/LAN74__/article/details/55189332
基础二叉树第层次遍历
首先呢,二叉树的构造就不用说啦。。。都知道,一种告诉你类满二叉树,还有一种呢。。就是两个遍历构造。。。这些已经都很熟悉了。。
看看题
Problem Description
已知一颗二叉树的前序遍历和中序遍历,求二叉树的层次遍历。
Input
输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。
Output
每组输出这颗二叉树的层次遍历。
Example Input
2
abc
bac
abdec
dbeac
Example Output
abc
abcde
很容易理解,我们来看看代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
char data;
struct node *l,*r;
};
struct node *creat(int n,char *str1,char *str2)
{
struct node *root;
int i;
if(n==0)
return NULL;
root = new node;
root -> data = str1[0];
for(i=0;i<n;i++)
{
if(str2[i] == str1[0])
break;
}
root -> l = creat(i,str1 + 1,str2);
root -> r = creat(n-1-i,str1 + i + 1,str2 + i + 1);
return root;
}
int p(struct node *root)
{
struct node *q[1100],*p;
int s = 0,e = 0;
if(!root)
return 0;
q[e++] = root;
while(s<e)
{
p = q[s++];
printf("%c",p->data);
if(p->l)
q[e++] = p -> l;
if(p -> r)
q[e++] = p -> r;
}
}
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
char s1[100010],s2[100010];
scanf("%s",s1);
scanf("%s",s2);
int m = strlen(s1);
struct node *root = creat(m,s1,s2);
p(root);
printf("\n");
}
}
只需要记住,用队列来记录这个节点
(1)根节点入队列
(2)输出队列第一个,如果有左孩子,左孩子入队列,如果有右孩子,右孩子入队列。
(3)重复步骤(2),直到队列为空