#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
char data;
int ltag,rtag;
struct node* lchild;
struct node* rchild;
}TBTNode;
TBTNode* pre;
TBTNode* Create()
{
TBTNode *root=NULL;
char data;
scanf("%c", &data);
if (data != '#')
{
root = (TBTNode*)malloc(sizeof(TBTNode));
root->ltag = root->rtag = 0;
root->data = data;
root->lchild = Create();
root->rchild = Create();
}
return root;
}
void Thread(TBTNode* root)
{
if (root!= NULL)
{
Thread(root->lchild);
if (pre != NULL && pre->rchild == NULL)
{
pre->rchild = root;
pre->rtag = 1;
}
if (root->lchild == NULL)
{
root->lchild = pre;
root->ltag = 1;
}
pre = root;
Thread(root->rchild);
}
}
void print(TBTNode* root)
{
while (root->lchild != NULL)
{
root = root->lchild;
}
printf("%c", root->data);//拿到第一个节点
while (root->rchild!= NULL)
{
if (root->rtag == 1)//有右子树和无右子树之分
{
root = root->rchild;
}
else
{
root=root->rchild;
while (root->ltag == 0)
{
root = root->lchild;
}
}
printf("%c", root->data);
}
}
int main()
{
TBTNode* head;
head=Create();
Thread(head);
print(head);
return 0;
}
下面是运行结果