采用中序线索链表存储结构,实现中序遍历
(1)定义线索链表的存储结构;
(2)按先序遍历创建一棵二叉链表树;
(3)实现二叉链表的中序线索化;
(4)实现中序线索链表的中序遍历。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef char TElemType;
/*2. 采用中序线索链表存储结构,实现中序遍历
(2)按先序遍历创建一棵二叉链表树;
(3)实现二叉链表的中序线索化;
(4)实现中序线索链表的中序遍历。
*/
typedef enum PointerTag { Link, Thread };//Link==0:指针 Thread==1:线索
typedef struct BiThrNode {
TElemType data;
struct BiThrNode *lchild, *rchild;//左右孩子指针
PointerTag LTag, RTag;//左右标志
}BiThrNode, *BiTrTree;
BiTrTree pre = (BiThrNode*)malloc(sizeof(BiThrNode));
//先序遍历创建一颗二叉链表树
void CreateBiTree(BiTrTree &T) {
char ch;
scanf("%c", &ch);
if (ch == '#') T = NULL;
else {
if (T = (BiThrNode *)malloc(sizeof(BiThrNode))) {
T->data = ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
}
//(3)实现二叉链表的中序线索化;
void InThreading(BiTrTree P) {
if (P) {
InThreading(P->lchild);
if (!P->lchild) {
P->LTag = Thread;
P->lchild = pre;
}
else P->LTag = Link;
if (!pre->rchild) {
pre->RTag = Thread;
pre->rchild = P;
}
else P->RTag = Link;
pre = P;
InThreading(P->rchild);
}
}
//加入头结点,中序线索二叉树
void InOrderThread_Head(BiTrTree &head, BiTrTree &P) {
head = (BiThrNode*)malloc(sizeof(BiThrNode));
head->rchild = head;//右指针回指
head->LTag = Link;
head->RTag = Thread;//建立头结点
if (!P) {
head->lchild = head;//空树
}
else {
head->lchild = P;
pre = head;
InThreading(P);//中序遍历进行中序线索化
pre->RTag = Thread;
pre->rchild = head;
head->rchild = pre;
}
}
//(4)实现中序线索链表的中序遍历。
void InOrderTraverse_Thr(BiTrTree T) {
BiTrTree p = new BiThrNode;
p = T->lchild;
while (p != T) {
while (p->LTag == Link) {
p = p->lchild;
}
printf("%c", p->data);
while (p->RTag == Thread && p->rchild != T) {
p = p->rchild;
printf("%c", p->data);
}
p = p->rchild;
}
}
int main()
{
pre->RTag = Thread;
pre->rchild = NULL;
BiTrTree P, s;
P = (BiThrNode *)malloc(sizeof(BiThrNode));
printf("请先序输入一颗树:");
CreateBiTree(P);
InOrderThread_Head(s, P);
printf("中序输出此树:");
InOrderTraverse_Thr(s);
printf("\n");
system("pause");
return 0;
}