tree.h
typedef struct TreeNode_s {
char val;//数据域
struct TreeNode_s *pLeft;//左结点
struct TreeNode_s *pRight;//右边结点
} TreeNode_t, *pTreeNode_t;
//辅助队列动态建立二叉树
typedef struct QueueNode_s {
pTreeNode_t NodeAddr; //队列的数据域存储的是二叉树结点的地址
struct QueueNode_s *pNext;
} QueueNode_t, *pQueueNode_t;
void preOrder(pTreeNode_t pRoot);
void inOrder(pTreeNode_t pRoot);
void postOrder(pTreeNode_t pRoot);
void buildBinaryTree(pTreeNode_t *ppRoot, pQueueNode_t *ppQueueFront, pQueueNode_t *ppQueueRear, char val);
main.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "tree.h"
#define N 10
int main() {
//固定大小数量建立二叉树
//char c[] = "ABCDEFGHIJ";
//pTreeNode_t arr[N] = { NULL };//索引数组
//for (int i = 0; i < N; ++i) {
// arr[i] = (pTreeNode_t)calloc(1, sizeof(TreeNode_t));
// arr[i]->val = c[i];
//}
//pTreeNode_t pRoot = arr[0];
//for (int i = 0, j = 1; j < N; ++j) {
// if (arr[i]->pLeft == NULL) {
// arr[i]->pLeft = arr[j];
// }
// else {
// arr[i]->pRight = arr[j];
// ++i;
// }
//}
pTreeNode_t pRoot = NULL;
pQueueNode_t pQueueFront = NULL;
pQueueNode_t pQueueRear = NULL;
char val;
while (scanf("%c", &val) != EOF) {
if (val == '\n') {
break;
}
buildBinaryTree(&pRoot, &pQueueFront, &pQueueRear, val);
}
preOrder(pRoot);
printf("\n");
inOrder(pRoot);
printf("\n");
postOrder(pRoot);
printf("\n");
}
//三种树的遍历方式
void preOrder(pTreeNode_t pRoot) {
if (pRoot) {
printf("%c", pRoot->val);
preOrder(pRoot->pLeft);
preOrder(pRoot->pRight);
}
}
void inOrder(pTreeNode_t pRoot) {
if (pRoot) {
inOrder(pRoot->pLeft);
printf("%c", pRoot->val);
inOrder(pRoot->pRight);
}
}
void postOrder(pTreeNode_t pRoot) {
if (pRoot) {
postOrder(pRoot->pLeft);
postOrder(pRoot->pRight);
printf("%c", pRoot->val);
}
}
//利用辅助队列层次动态建立二叉树,队列中存储的是每个二叉树结点的地址,即辅助队列是用来管理二叉树结点的地址的
void buildBinaryTree(pTreeNode_t *ppRoot, pQueueNode_t *ppQueueFront, pQueueNode_t *ppQueueRear, char val) {
//构造二叉树结点
pTreeNode_t pTreeNode = (pTreeNode_t)calloc(1, sizeof(TreeNode_t));
pTreeNode->val = val;
//构造队列结点
pQueueNode_t pQueueNode = (pQueueNode_t)calloc(1, sizeof(QueueNode_t));
pQueueNode->NodeAddr = pTreeNode;
if (*ppRoot == NULL) {//给二叉树和队列插入第一个结点
*ppRoot = pTreeNode;
*ppQueueFront = pQueueNode;
*ppQueueRear = pQueueNode;
}
else {
//尾插法入队
(*ppQueueRear)->pNext = pQueueNode;
*ppQueueRear = pQueueNode;
pQueueNode_t pQueueCur = *ppQueueFront;//队首
if (pQueueCur->NodeAddr->pLeft == NULL) {
//把新结点插入到队首所指的二叉树结点的左孩子
pQueueCur->NodeAddr->pLeft = pTreeNode;
}
else {
pQueueCur->NodeAddr->pRight = pTreeNode;
//放好右孩子之后,要出队,头部删除法
*ppQueueFront = pQueueCur->pNext;
free(pQueueCur);
pQueueCur = NULL;
}
}
}