#include<stdio.h>
#include<stdlib.h>
struct tree{
int data;// [树的结构]
struct tree *left,*right;
};
struct line{
struct tree*link;
struct line *next;
};//队列 用于层序输出树 [队列的节点元素结构]
struct line* Creat_line(){// [队列的头结点创建]
struct line* p;
p=(struct line*)malloc(sizeof(struct line));// 在用队列输出树时,应该将树的结构体增加队列的指针,其中,加入的单个树的结构体由于其本身指针指向了左右子树,
p->next=NULL;// 为了不丢失左右子树的地址,或更方便的遍历左右子树,不能只将树的data域传入队列。
p->link=NULL;
return p;
}
struct tree*Creat_tree(int Data){ // [树的头结点创建]
struct tree*p;
p=(struct tree*)malloc(sizeof(struct tree));
p->left=NULL;
p->right=NULL;
p->data=Data;
return p;
}
struct line* pop_line(struct tree*p_tree,struct line*rear_line){
struct line*new_line;
if(p_tree==NULL)
return rear_line;
new_line=(struct line*)malloc(sizeof(struct line));
rear_line->next=new_line;
new_line->link=p_tree;
rear_line=rear_line->next;
new_line->next=NULL;
return rear_line;
}
void push_line(struct line*head_line){
struct line*old_line;
old_line=(struct line*)malloc(sizeof(struct line));
old_line=head_line->next;
head_line->next=old_line->next;
free(old_line);
}
void print_line(struct tree*head_tree,struct line*head_line){// [对队列进行树的层序输出]
struct tree*p_tree;
struct line*rear_line=head_line;
p_tree=head_tree;
rear_line=pop_line(head_tree,rear_line);
do{
rear_line=pop_line(head_line->next->link->left,rear_line);
rear_line=pop_line(head_line->next->link->right,rear_line);
printf("%d ",head_line->next->link->data);
push_line(head_line);
}while(head_line->next!=NULL);
}
struct tree* add_tree(struct tree*p,int Data,int dire){// [树的加入操作]
struct tree *new;
new=(struct tree*)malloc(sizeof(struct tree));
if(dire==1)
p->left=new;
else
p->right=new;
new->data=Data;
new->left=NULL;
new->right=NULL;
return new;
}
void change_tree(struct tree*p,int Data){ //[此步可省略]
p->data=Data;
}
struct tree*bianli_tree(struct tree*p,int dire){// [对树的遍历]
if(dire==1)
p=p->left;
else
p=p->right;
return p;
}
int main(void){
struct tree*head_tree,*p;
struct line*head_line;
int i,Data,dire;
scanf("%d",&Data);
p=head_tree=Creat_tree(Data);// [树头结点已创建]
head_line=Creat_line();// [队列头结点已创建]
do{
printf("1向左遍历,2向右遍历 0退出 3重新遍历 4增加 5修改");
scanf("%d",&i);
if(i==1||i==2)
p=bianli_tree(p,i);
if(i==3)
p=head_tree;
if(i==4){
printf("请先输入增加的子树的数据在输入增加方向");
scanf("%d%d",&Data,&dire);
p=add_tree(p,Data,dire);
}
if(i==5){
printf("请输入修改的树结点的新数据:");
scanf("%d",&Data);
change_tree(p,Data);
}
}while(i!=0);
print_line(head_tree,head_line);
return 0;
}
重点在于在队列入队是加入树结点的数据域的同时保存其儿子结点的地址。
这里用了结构体的简单嵌套。
这是当前能想到的简便易懂的队列层序遍历方法,代码繁琐,有待改进