二叉树的创建、递归与非递归遍历、层次遍历、销毁。
(运行环境:vs2019)
所写二叉树图例:
遍历结果
先序(先根再左再右):1 2 4 5 3 6 7
中序(先左再中再右):4 2 5 1 6 3 7
后序(先左再右再中):4 5 2 6 7 3 1
层次:1 2 3 4 5 6 7
实验结果:完成
全码:
#include<stdio.h>
#include<stdlib.h>
#define M 50
typedef struct Tree {
int data;
struct Tree* LChild;
struct Tree* RChild;
}Tree, * BitTree;
BitTree createTree() {
int data, t;
scanf_s("%d", &data);
t = getchar();
if (data == -1) { //输入-1表示NULL
return NULL;
}
else {
BitTree node = (BitTree)malloc(sizeof(Tree));
node->data = data;
printf("请输入%d左子树:", data);
node->LChild = createTree();
printf("请输入%d右子树:", data);
node->RChild = createTree();
return node;
}
}
//先序、中序、后序递归遍历
void Preorder(BitTree T) {
if (T == NULL) {
return;
}
printf("%d ", T->data);
Preorder(T->LChild);
Preorder(T->RChild);
}
void Inorder(BitTree T) {
if (T == NULL)
{
return;
}
Inorder(T->LChild);
printf("%d ", T->data);
Inorder(T->RChild);
}
void Postorder(BitTree T) {
if (T == NULL) {
return;
}
Postorder(T->LChild);
Postorder(T->RChild);
printf("%d ", T->data);
}
//层次遍历
void LAYERorder(BitTree T) {
BitTree Q[M], p;
int front, rear;
if (T != NULL) {
Q[0] = T;//根节点入队头
front = -1;
rear = 0;
while (front < rear) {//rear上升速度大于front
p = Q[++front];//一次循环输出一次
printf("%d ", p->data);
//若三层只要两次就入队完成
if (p->LChild != NULL) {
Q[++rear] = p->LChild;
}
if (p->RChild != NULL) {
Q[++rear] = p->RChild;
}
}
}
}
//先序、中序、后序非递归遍历
void PREORDER(BitTree T) {
BitTree Stack[M], p = T;
int top = -1;
if (T != NULL) {
while (p != NULL || top != -1) {
while (p != NULL) {//左进
Stack[++top] = p;
printf("%d ", p->data);//进栈顺序就是先序遍历顺序
p = p->LChild;
}
p = Stack[top--];//记录当前栈,再退一栈
p = p->RChild;
}
}
}
void INORDER(BitTree T) {
BitTree Stack[M], p = T;
int top = -1;
if (T != NULL) {
while (p != NULL || top != -1) {
while (p != NULL) {
Stack[++top] = p;
p = p->LChild;
}
p = Stack[top--];
printf("%d ", p->data);
p = p->RChild;
}
}
}
void POSTORDER(BitTree T) {
BitTree stack1[M], p = T;
int stack2[M];
int flag, top = -1;
if (T != NULL) {
while (p != NULL || top != -1) {
while (p != NULL) {
stack1[++top] = p;
stack2[top] = 0;//先把节点标记为0
p = p->LChild;
}
p = stack1[top];
flag = stack2[top--];//出栈
if (flag == 0) {
stack1[++top] = p;
stack2[top] = 1;//再标记为1,然后到出栈
p = p->RChild;
}
else {
printf("%d ", p->data);//输出标记为1的节点
p = NULL;
}
}
}
}
void DESTORYBT(BitTree T) {
if (T != NULL) {
DESTORYBT(T->LChild);
DESTORYBT(T->RChild);
free(T);
}
}
void CLEARBT(BitTree& T) {
DESTORYBT(T);
T = NULL;
}
int main() {
BitTree BT;
BT = createTree();
puts("先序遍历:");
PREORDER(BT);
puts("\n先序递归遍历:");
Preorder(BT);
puts("\n中序遍历:");
INORDER(BT);
puts("\n中序递归遍历:");
Inorder(BT);
puts("\n后序遍历:");
POSTORDER(BT);
puts("\n后序递归遍历:");
Postorder(BT);
puts("\n层次递归遍历:");
LAYERorder(BT);
CLEARBT(BT);
if (BT == NULL) {
puts("\n已释放完全!");
}
return 0;
}