构造先序线索二叉树:先先序创建二叉树,然后初始化标记为为0,再进行先序二叉树的线索化。先序遍历树中的每一个结点,访问每一对前驱和后继。如果当前访问结点左孩子为空,则将其左指针域指向前驱结点,并将标志域置为1;如果当前结点的前驱结点右孩子为空,则将右孩子指向他的后继结点,并将标志域置为1。(特别注意线索化的时候对最后一个结点的处理)
先序线索二叉树的遍历:如果当前结点的左标记域为0,他的后继结点即为左孩子,更新当前结点为后继结点;否则,他的后继结点为右孩子,更新当前结点为后继结点。重复上述步骤,直到遍历完树中的每一个结点。(中心思想:前驱找后继的过程)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef char ElemType;
typedef struct BiThrNode {
ElemType data;
struct BiThrNode* lchild, * rchild;
int ltag, rtag;
}BiThrNode,*BiThrTree;
//先序建树
void createThrTree(BiThrTree &T) {
ElemType ch;
scanf("%c", &ch);
if (ch == '#') {
T = NULL;
}
else {
T = (BiThrNode*)malloc(sizeof(BiThrNode));
T->data = ch;
createThrTree(T->lchild);
createThrTree(T->rchild);
}
}
//初始化标记位
void initialThrTree(BiThrTree &T) {
if (T != NULL) {
T->ltag = 0;
T->rtag = 0;
initialThrTree(T->lchild);
initialThrTree(T->rchild);
}
}
//先序线索化二叉树
BiThrNode* prenode = NULL;
void PreThrTree(BiThrNode* pcurnode) {
if (pcurnode != NULL) {
if (pcurnode->lchild == NULL) {
pcurnode->lchild = prenode;
pcurnode->ltag = 1;
}
if (prenode != NULL && prenode->rchild == NULL) {
prenode->rchild = pcurnode;
prenode->rtag = 1;
}
prenode = pcurnode;
if (pcurnode->ltag== 0) {
PreThrTree(pcurnode->lchild);
}
if (pcurnode->rtag== 0) {
PreThrTree(pcurnode->rchild);
}
}
}
//先序线索主过程
void creatpreThrTree(BiThrNode* T) {
prenode = NULL;//pre初始化为空
if (T != NULL) {//非空二叉树才能线索化
PreThrTree(T);//先序线索二叉树
if (prenode->rchild == NULL) //处理最后一个结点
prenode->rtag = 1;
}
}
void preOrderThrTree(BiThrTree T) {
BiThrNode* pnode = T;
BiThrNode* pnextnode = NULL;
while (pnode != NULL) {
if (pnode->ltag == 0) {
printf("%c", pnode->data);
pnextnode = pnode->lchild;
pnode = pnextnode;
}
else {
printf("%c", pnode->data);
pnextnode = pnode->rchild;
pnode = pnextnode;
}
}
}
//AB#D##CE###
int main() {
BiThrTree Thr = NULL;
createThrTree(Thr);
initialThrTree(Thr);
creatpreThrTree(Thr);
preOrderThrTree(Thr);
return 0;
}