#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
typedef struct node
{
char data;
struct node *lchild, *rchild;
int ltag, rtag;
}*Tree, Tnode;
static void CreateTree(Tree *T);
static void ThreadTree(Tree *T);
static void PrintThreadTree(Tree T);
static Tree NextNode(Tree curPtr);
int main(void)
{
Tree T = NULL;
CreateTree(&T);
ThreadTree(&T);
PrintThreadTree(T);
getch();
return 0;
}
static void CreateTree(Tree *T)
{
int ia;
ia = getchar();
if (ia == '/')
{
*T = NULL;
}
else
{
if (((*T) = (Tree)malloc(sizeof(Tnode))) == NULL)
{
exit(1);
}
(*T) -> data = ia;
(*T) -> lchild = (*T) -> rchild = NULL;
CreateTree(&(*T) -> lchild);
CreateTree(&(*T) -> rchild);
}
}
static void ThreadTree(Tree *T)
{
static Tree prePtr = NULL; /* prePtr = previous pointer */
if (*T != NULL)
{
ThreadTree(&(*T) -> lchild); /* thread left tree */
if ((*T) -> lchild == NULL)
{
(*T) -> ltag = 1;
}
if ((*T) -> rchild == NULL)
{
(*T) -> rtag = 1;
}
if (prePtr -> rtag == 1)
{
prePtr -> rchild = *T;
}
if ((*T) -> ltag == 1)
{
(*T) -> lchild = prePtr;
}
prePtr = *T;
ThreadTree(&(*T) -> rchild); /* thread right tree */
}
}
static void PrintThreadTree(Tree curPtr)
{ /* curPtr = current pointer */
while (curPtr -> lchild != NULL)
{
curPtr = curPtr -> lchild; /* search the first print node */
}
while (curPtr != NULL)
{
printf("%c -> ", curPtr -> data);
curPtr = NextNode(curPtr);
}
printf("NULL\n");
}
static Tree NextNode(Tree curPtr)
{
if (curPtr -> rtag == 1)
{
return curPtr -> rchild;
}
else
{
curPtr = curPtr -> rchild;
while (curPtr -> ltag != 1)
{
curPtr = curPtr -> lchild;
}
return curPtr;
}
}