|
//二叉树的二叉线索存储表示
#include<stdio.h>
#include<iostream.h>
#include<stdlib.h>
#define NULL 0
#define OVERFLOW -1
#define OK 1
#define ERROR 0
typedef enum PointerTag{Link=0, Thread};
typedef char TElemType;
typedef char Status ;
typedef struct BiThrNode{
TElemType data;
struct BiThrNode *lchild, *rchild;
PointerTag LTag, RTag;
}BiThrNode, *BiTree;
BiTree CreateBiTree()
{
TElemType ch;
BiTree T;
scanf("%c",&ch);
if(ch=='#')
T=NULL;
else{
T=(BiTree)malloc(sizeof(BiThrNode));
T->data=ch;
T->lchild=CreateBiTree(); //这是中许建立?
T->rchild=CreateBiTree();
}
return T;
}
void InThreading(BiTree p){
if(p){
BiTree pre=NULL;
pre->LTag=Link;
pre->RTag=Thread;
pre->rchild=pre;
if(!p)pre->lchild=pre;
else pre->lchild=p;
InThreading(p->lchild);
if(!p->lchild){p->LTag=Thread; p->lchild=pre;}
if(!pre->rchild){pre->RTag=Thread; pre->rchild=p;}
pre=p;
InThreading(p->rchild);
}
}
Status InOrderThreading(BiTree &Thrt, BiTree T){
//中序遍历二差树,并将其中序线索化,Thrt指向头结点
Thrt->LTag=Link;
Thrt->RTag=Thread;
Thrt->rchild=Thrt;
if(!T)Thrt->lchild=Thrt;
else{
BiTree pre;
Thrt->lchild=T;
pre=Thrt;
InThreading(T);
pre->rchild=Thrt;//最后一个结点线索化
pre->RTag=Thread;
Thrt->rchild=pre;
}
return OK;
}
//遍历
Status InOrderTraverse(BiTree T, Status (*Visit)(TElemType e)){
BiThrNode *p;
p=T->lchild;
while(p!=T){
while(p->LTag==Link)p=p->lchild;
if(!Visit(p->data)) return ERROR;
while(p->RTag==Thread&&p->rchild!=T){
p=p->rchild;
Visit(p->data);
}
p=p->rchild;
}
return OK;
}
Status Visit(TElemType e){
cout<<e;
return e;
}
void main(){
BiTree Thrt, t;
if(!(Thrt = (BiTree)malloc(sizeof(BiThrNode)))) exit (OVERFLOW);
cout<<"a";
t=CreateBiTree();
// InOrderThreading(Thrt, t);
cout<<"jdiue";
InOrderTraverse(t,Visit);
} |
|