实验内容及要求:
设二叉树结点数据域为字符类型,从键盘输入先序递归遍历字符序列(用#字符表示NULL指针域)建立二叉链表存储结构,然后实现中序线索化。基于中序穿线二叉树存储结构定义first,next,last,previous四个函数并实现中序线索二叉树中序遍历(正序与逆序)非递归算法,输出遍历结果。
实验目的:掌握中序穿线二叉树的建立与基本操作。
#include "iostream"
using namespace std;
typedef enum {Link,Thread} PointerTag;
typedef struct ThreadNode {
char data;
struct ThreadNode* lchild, * rchild;
PointerTag ltag, rtag;
}ThreadNode;
//创建一颗二叉树,注意这里要初始化其标志位都为Link
void Create(ThreadNode** T) {
char c;
cin >> c;
if (c=='#')
{
(*T) = nullptr;
}
else
{
(*T) = (ThreadNode*)malloc(sizeof(ThreadNode));
(*T)->data = c;
(*T)->ltag = Link;
(*T)->rtag = Link;
Create(&(*T)->lchild);
Create(&(*T)->rchild);
}
}
//中序线索化二叉树
void inThread(ThreadNode* T){
//这里的pre变量要么定义到函数外,要么用static修饰
static ThreadNode* pre = nullptr;
if (T)
{
inThread(T->lchild);
if (T->lchild==nullptr)
{
T->ltag = Thread;
T->lchild = pre;
}
if (pre != nullptr && pre->rchild==nullptr)
{
pre->rtag = Thread;
pre->rchild = T;
}
pre = T;
inThread(T->rchild);
}
}
//求后继
ThreadNode* next(ThreadNode* T) {
ThreadNode* result = nullptr;
if (T->rtag==Thread)
{
result = T->rchild;
}
else if (T->rtag==Link)
{
result = T->rchild;
while (result && result->ltag==Link)
{
result = result->lchild;
}
}
return result;
}
//中序遍历(正序)
void inOrder(ThreadNode* T) {
ThreadNode* p = T;
while (p->ltag==Link)
{
p = p->lchild;
}
while (p)
{
printf("%c ", p->data);
p = next(p);
}
}
//求前驱
ThreadNode* previous(ThreadNode* T) {
ThreadNode* result = nullptr;
if (T->ltag==Thread)
{
result = T->lchild;
}
else
{
result = T->lchild;
while (result->rtag==Link)
{
result = result->rchild;
}
}
return result;
}
//中序遍历(逆序)
void inOrderReverse(ThreadNode* T) {
ThreadNode* p = T;
while (p->rchild!=nullptr)
{
p = p->rchild;
}
while (p)
{
printf("%c ", p->data);
p = previous(p);
}
}
ThreadNode* first(ThreadNode* T) {
while (T && T->ltag == Link) {
T = T->lchild;
}
return T;
}
ThreadNode* last(ThreadNode* T) {
while (T->rchild!=nullptr)
{
T = T->rchild;
}
return T;
}
//测试
int main() {
ThreadNode* T = nullptr;
Create(&T);
inThread(T);
inOrder(T);
printf("\n");
inOrderReverse(T);
}
参考博客:(4条消息) 线索二叉树的实现、中序遍历(正序、逆序)C语言实现_XduStudent的博客-CSDN博客
输入:ABD##E##CF##G##
输出:D B E A F C G
G C F A E B D