用C语言将二叉树的顺序存储结构转换成二叉链存储结构并输出。
时间: 2024-06-13 22:09:23 浏览: 105
以下是将二叉树的顺序存储结构转换成二叉链存储结构的C语言代码,并输出二叉链存储结构:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct BiTNode {
char data;
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
void CreateBiTree(BiTree *T, char *bt, int i) {
char ch = bt[i];
if (ch == '#') {
*T = NULL;
} else {
*T = (BiTree) malloc(sizeof(BiTNode));
(*T)->data = ch;
CreateBiTree(&(*T)->lchild, bt, 2 * i);
CreateBiTree(&(*T)->rchild, bt, 2 * i + 1);
}
}
void PreOrderTraverse(BiTree T) {
if (T) {
printf("%c ", T->data);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
}
void InOrderTraverse(BiTree T) {
if (T) {
InOrderTraverse(T->lchild);
printf("%c ", T->data);
InOrderTraverse(T->rchild);
}
}
void PostOrderTraverse(BiTree T) {
if (T) {
PostOrderTraverse(T->lchild); PostOrderTraverse(T->rchild);
printf("%c ", T->data);
}
}
void CreateBiTreeByArray(BiTree *T, char *bt, int i, int len) {
if (i >= len) {
return;
}
if (bt[i] == '#') {
*T = NULL;
} else {
*T = (BiTree) malloc(sizeof(BiTNode));
(*T)->data = bt[i];
CreateBiTreeByArray(&(*T)->lchild, bt, 2 * i + 1, len);
CreateBiTreeByArray(&(*T)->rchild, bt, 2 * i + 2, len);
}
}
void InOrderTraverseThread(BiTree T, BiTree *pre) {
if (T) {
InOrderTraverseThread(T->lchild, pre);
if (!T->lchild) {
T->lchild = *pre;
T->ltag = 1;
}
if (*pre && !(*pre)->rchild) {
(*pre)->rchild = T;
(*pre)->rtag = 1;
}
*pre = T;
InOrderTraverseThread(T->rchild, pre);
}
}
void InOrderThread(BiTree *p, BiTree T) {
*p = (BiTree) malloc(sizeof(BiTNode));
(*p)->ltag = 0;
(*p)->rtag = 1;
(*p)->rchild = *p;
if (!T) {
(*p)->lchild = *p;
} else {
(*p)->lchild = T;
BiTree pre = *p;
InOrderTraverseThread(T, &pre);
pre->rchild = *p;
pre->rtag = 1;
(*p)->rchild = pre;
}
}
int main() {
char bt[MAXSIZE];
printf("请输入二叉树的顺序存储结构(用#表示空节点):\n");
scanf("%s", bt);
BiTree T;
CreateBiTree(&T, bt, 1);
printf("二叉树的前序遍历结果为:");
PreOrderTraverse(T);
printf("\n");
printf("二叉树的中序遍历结果为:");
InOrderTraverse(T);
printf("\n");
printf("二叉树的后序遍历结果为:");
PostOrderTraverse(T);
printf("\n");
BiTree p;
InOrderThread(&p, T);
printf("二叉树的中序线索化结果为:\n");
BiTree q = p->rchild;
while (q != p) {
while (q->ltag == 0) {
q = q->lchild;
}
printf("%c ", q->data);
while (q->rtag == 1 && q->rchild != p) {
q = q->rchild;
printf("%c ", q->data);
}
q = q->rchild;
}
printf("\n");
return 0;
}
```
阅读全文