按层次遍历的顺序构建二叉树(非递归)
切记:千万不要返回一个空指针(NULL pointer)
#include<stdlib.h>
#define MAX 50
typedef struct BTNode{
int val;
struct BTNode* lchild;
struct BTNode* rchild;
}BTNode;
void init(BTNode** bt){
*bt=NULL;
}
void insert_level(int x,BTNode** bt){
if(*bt==NULL){
*bt=malloc(sizeof(BTNode));
(*bt)->lchild=(*bt)->rchild=NULL;
(*bt)->val=x;
}else{
BTNode* que[MAX];
int front=0,rear=0;
BTNode* p=*bt;
rear=(rear+1)%50;
que[rear]=p;
while(front!=rear){
front=(front+1)%50;
p=que[front];
if(p->lchild){
rear=(rear+1)%50;
que[rear]=p->lchild;
}else{
p->lchild=malloc(sizeof(BTNode));
p=p->lchild;
p->lchild=p->rchild=NULL;
p->val=x;
break;
}
if(p->rchild){
rear=(rear+1)%50;
que[rear]=p->rchild;
}else{
p->rchild=malloc(sizeof(BTNode));
p=p->rchild;
p->lchild=p->rchild=NULL;
p->val=x;
break;
}
}
}
}
void makeTree(BTNode** bt){
init(bt);
int val;
while(scanf("%d",&val)==1){
insert_level(val,bt);
}
}
void display(BTNode* bt){
if(bt){
printf("%d ",bt->val);
display(bt->lchild);
display(bt->rchild);
}
}