# include<math.h>
# include<iostream>
# include<stdio.h>
using namespace std;
int num[30] = {1,2,4,0,0,5,0,0,3,6,0,0,7,0,0};
int i = 0;
typedef int Elemtype;
typedef struct ThreadTNode{
Elemtype data;
struct ThreadTNode *lchild,*rchild;
int ltag = 0,rtag = 0;
}ThreadTNode,*ThreadTree;
ThreadTNode *pre = NULL;
void printNode(ThreadTNode *p){
printf("%d ",p->data);
}
ThreadTNode *find_LastInNode(ThreadTNode *p){
while (p->rtag==0)
p = p->rchild;
return p;
}
ThreadTNode *find_PreInNode(ThreadTNode *p){
if(p->ltag == 0)
return find_LastInNode(p->lchild);
else if(p->ltag == 1)
return p->lchild;
}
void RevInOrder(ThreadTree T){
for(ThreadTNode *p = find_LastInNode(T);p!=NULL;p=find_PreInNode(p)){
printNode(p);
}
}
ThreadTNode *find_FirstInThread(ThreadTNode *p){
while(p->ltag == 0)
p = p->lchild;
return p;
}
ThreadTNode *find_NextInNode(ThreadTNode *p){
if(p->rtag==0)
return find_FirstInThread(p->rchild);
else if(p->rtag==1)
return p->rchild;
}
void InOder(ThreadTree T){
for(ThreadTNode *p = find_FirstInThread(T);p!=NULL;p = find_NextInNode(p))
printNode(p);
}
void inThread(ThreadTree &p){
if(p!=NULL){
inThread(p->lchild);
if(p->lchild==NULL){
p->lchild = pre;
p->ltag = 1;
}
if(pre!=NULL && pre->rchild==NULL){
pre->rchild = p;
pre->rtag = 1;
}
pre = p;
printf("%d ",p->data);
inThread(p->rchild);
}
}
void preThread(ThreadTree &p){
if(p!=NULL){
if(p->lchild==NULL){
p->lchild = pre;
p->ltag = 1;
}
if(pre!=NULL && pre->rchild==NULL){
pre->rchild = p;
pre->rtag = 1;
}
pre = p;
if(p->ltag==0)
preThread(p->lchild);
preThread(p->rchild);
}
}
void postThread(ThreadTree &p){
if(p!=NULL){
postThread(p->lchild);
postThread(p->rchild);
if(p->lchild==NULL){
p->lchild = pre;
p->ltag = 1;
}
if(pre!=NULL && pre->rchild==NULL){
pre->rchild = p;
pre->rtag = 1;
}
pre = p;
}
}
void visit(ThreadTree &T){
if(T->lchild==NULL){
T->lchild = pre;
T->ltag = 1;
}
if(pre!=NULL && pre->rchild==NULL){
pre->rchild = T;
pre->rtag = 1;
}
pre = T;
printf("%d ",T->data);
}
void preOrder(ThreadTree &T){
if(T!=NULL){
visit(T);
if(T->ltag==0)
preOrder(T->lchild);
preOrder(T->rchild);
}
}
void inOrder(ThreadTree &T){
if(T!=NULL){
inOrder(T->lchild);
visit(T);
inOrder(T->rchild);
}
}
void postOrder(ThreadTree &T){
if(T!=NULL){
postOrder(T->lchild);
postOrder(T->rchild);
visit(T);
}
}
void buildTree(ThreadTree &T){
int el;
el = num[i];i++;
if(el==0)
T=NULL;
else{
T = (ThreadTNode *)malloc(sizeof(ThreadTNode));
T->data = el;
T->ltag = 0;
T->rtag = 0;
buildTree(T->lchild);
buildTree(T->rchild);
}
}
void createinThread1(ThreadTree &T){
pre = NULL;
if(T!=NULL){
inOrder(T);
if(pre->rchild == NULL)
pre->rtag = 1;
}
}
void createinThread2(ThreadTree &T){
pre = NULL;
if(T!=NULL){
inThread(T);
if(pre->rchild == NULL)
pre->rtag = 1;
}
}
int main(void){
ThreadTree T1;
T1 = NULL;
buildTree(T1);
createinThread2(T1);
printf("\n\n\n");
RevInOrder(T1);
printf("\n\n\n");
InOder(T1);
return 0;
}
最后用逆序和非递归可以进行验证.
|