二叉树
顾名思义,二叉树即为至多有两个分支的树。故表示二叉树的链表中的结点至少包括三个域:数据域、左、右指针域。其层序遍历需要用一个队列实现。
相关代码
结构体创建
//树中结点
typedef struct BTNode{
char element;
BTNode* left;
BTNode* right;
}*BTNodePtr;
//队列创建
typedef struct Queue{
BTNodePtr* nodePtrs;
int front;
int rear;
}*QueuePtr;
初始化队列
void initQueue(QueuePtr Q){
Q=(QueuePtr)malloc(sizeof(struct Queue));
Q->nodePtrs=(BTNodePtr*)malloc(QUEUE_SIZE*sizeof(struct BTNode));
Q->front=0;
Q->rear=0;
}
入队
void enqueue(QueuePtr Q,BTNodePtr t){
printf("入队%c\n",t->element);
if((Q->rear+1)%QUEUE_SIZE==Q->front){
printf("队满\n");
return;
}
Q->nodePtrs[Q->rear]=t;
Q->rear=(Q->rear++)%QUEUE_SIZE;
}
出队
BTNodePtr dequeue(QueuePtr Q){
if(Q->rear==Q->front){
printf("队空无法出队\n");
return NULL;
}
Q->front=(Q->front+1)%QUEUE_SIZE;
printf("%c出队\n",Q->nodePtrs[Q->front]->element);
return Q->nodePtrs[Q->front];
}
构造一个结点
BTNodePtr constructBTNode(char e){
BTNodePtr resultPtr=(BTNodePtr)malloc(sizeof(struct BTNode));
resultPtr->element=e;
resultPtr->left=NULL;
resultPtr->right=NULL;
return resultPtr;
}
将字符串转化成二叉树
BTNodePtr stringToBtree(char* parastring){
int i=0;
char ch;
QueuePtr Q;
BTNodePtr parent,leftchild,rightchild;
initQueue(Q);
ch=parastring[i];
BTNodePtr resultHeader=constructBTNode(ch);
enqueue(Q,resultHeader);
while(Q->front!=Q->rear){
parent=dequeue(Q);
//左子树
i++;
ch=parastring[i];
if(ch=='#'){
parent->left=NULL;
}
else{
leftchild=constructBTNode(ch);
enqueue(Q,leftchild);
parent->left=leftchild;
}
//右子树
i++;
ch=parastring[i];
if(ch=='#'){
parent->right=NULL;
}
else{
rightchild=constructBTNode(ch);
enqueue(Q,rightchild);
parent->right=rightchild;
}
}
return resultHeader;
}
遍历二叉树
层序遍历
void levelwise(BTNodePtr paraTreePtr){
QueuePtr Q;
initQueue(Q);
char tempstring[100];
int i=0;
BTNodePtr tempNodePtr;
enqueue(Q,paraTreePtr);
while(Q->front!=Q->rear){
tempNodePtr=dequeue(Q);
tempstring[i++]=tempNodePtr->element;
if(tempNodePtr->left!=NULL){
enqueue(Q,tempNodePtr->left);
}
if(tempNodePtr->right!=NULL){
enqueue(Q,tempNodePtr->right);
}
}
tempstring[i]='\0';
printf("层序遍历:%s\n",tempstring);
}
前序遍历
以中左右的顺序遍历
void preorder(BTNodePtr tempPtr){
if (tempPtr == NULL){
return;
}
printf("%c", tempPtr->element);
preorder(tempPtr->left);
preorder(tempPtr->right);
}
中序遍历
以左中右的顺序遍历
void inorder(BTNodePtr tempPtr){
if (tempPtr == NULL) {
return;
}
inorder(tempPtr->left);
printf("%c", tempPtr->element);
inorder(tempPtr->right);
}
后序遍历
以左右中的顺序遍历
void postorder(BTNodePtr tempPtr){
if (tempPtr == NULL) {
return;
}
postorder(tempPtr->left);
postorder(tempPtr->right);
printf("%c", tempPtr->element);
}
主函数
int main(){
char* tempstring = "acde#bf######";
BTNodePtr tempHeader=stringToBtree(tempstring);
printf("前序:");
preorder(tempHeader);
printf("\n");
printf("中序:");
inorder(tempHeader);
printf("\n");
printf("后序:");
postorder(tempHeader);
printf("\n");
printf("层序:");
levelwise(tempHeader);
printf("\n");
}