已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
Input
2
abd,,eg,,,cf,,,
xnl,,i,,u,,
Output
abcdefg
xnuli
两种方法实现二叉树的层序遍历
1、说明
层序遍历所要解决的问题很好理解,就是按二叉树从上到下,从左到右依次打印每个节点中存储的数据。如下图:
先序遍历:A → B → D → C
中序遍历:B → D → A → C
后续遍历:D → B → C → A
层序遍历:A → B → C → D
2、实现
队列实现:
仔细看看层序遍历过程,其实就是从上到下,从左到右依次将每个数放入到队列中,然后按顺序依次打印就是想要的结果。
实现过程
1、首先将二叉树的根节点push到队列中,判断队列不为NULL,就输出队头的元素,
2、判断节点如果有孩子,就将孩子push到队列中,
3、遍历过的节点出队列,
4、循环以上操作,直到Tree == NULL。
数组实现:
实现过程
1、创建一个指针数组,保存二叉树结构体指针,
2、保存二叉树根节点,再申请变量 in、out ,控制数组,在遍历过程中,始终能找到节点和该节点的前一个节点,
3、循环以上过程。
#include
#include
#include
struct node{
char c;
struct node *lt, *rt;
};
char s[50];
int flag;
struct node *create(){
struct node *root;
root = (struct node *)malloc(sizeof(struct node));
if(s[flag] == ','){
flag++;
return NULL;
}
else{
root -> c =s[flag++];
root -> lt = create();
root -> rt = create();
}
return root;
}
void hierarchical(struct node *root){
int in = 0, out = 0;
struct node *hie[50];
hie[in++] = root;
while(out < in){
if(hie[out]){
printf("%c", hie[out] -> c);
hie[in++] = hie[out] -> lt;
hie[in++] = hie[out] -> rt;
}
out++;
}
//printf("%d %d\n", out, in);
}
int main(){
int t, i;
scanf("%d", &t);
for(i = 0; i < t; i++){
flag = 0;
scanf("%s", &s);
struct node *root;
root = create();
hierarchical(root);
printf("\n");
}
return 0;
}