本文是数据结构基础系列(6):树和2叉树中第14课时线索2叉树的例程。
#include #include #define MaxSize 100 typedef char ElemType; typedef struct node
{
ElemType data; int ltag,rtag; struct node *lchild; struct node *rchild;
} TBTNode; void CreateTBTNode(TBTNode * &b,char *str)
{
TBTNode *St[MaxSize],*p=NULL; int top=-1,k,j=0; char ch;
b=NULL; ch=str[j]; while (ch!=�) { switch(ch)
{ case (:
top++;
St[top]=p;
k=1; break; case ):
top--; break; case ,:
k=2; break; default:
p=(TBTNode *)malloc(sizeof(TBTNode));
p->data=ch;
p->lchild=p->rchild=NULL; if (b==NULL) b=p; else { switch(k)
{ case 1:
St[top]->lchild=p; break; case 2:
St[top]->rchild=p; break;
}
}
}
j++;
ch=str[j];
}
} void DispTBTNode(TBTNode *b)
{ if (b!=NULL)
{ printf("%c",b->data); if (b->lchild!=NULL || b->rchild!=NULL)
{ printf("(");
DispTBTNode(b->lchild); if (b->rchild!=NULL) printf(",");
DispTBTNode(b->rchild); printf(")");
}
}
}
TBTNode *pre; void Thread(TBTNode *&p)
{ if (p!=NULL)
{
Thread(p->lchild); if (p->lchild==NULL) {
p->lchild=pre; p->ltag=1;
} else p->ltag=0; if (pre->rchild==NULL) {
pre->rchild=p; pre->rtag=1;
} else pre->rtag=0;
pre=p;
Thread(p->rchild); }
}
TBTNode *CreaThread(TBTNode *b) {
TBTNode *root;
root=(TBTNode *)malloc(sizeof(TBTNode)); root->ltag=0;
root->rtag=1;
root->rchild=b; if (b==NULL) root->lchild=root; else {
root->lchild=b;
pre=root; Thread(b); pre->rchild=root; pre->rtag=1;
root->rchild=pre; } return root;
} void ThInOrder(TBTNode *tb)
{
TBTNode *p=tb->lchild; while (p!=tb)
{ while (p->ltag==0) p=p->lchild; printf("%c ",p->data); while (p->rtag==1 && p->rchild!=tb)
{
p=p->rchild; printf("%c ",p->data);
}
p=p->rchild;
}
} int main()
{
TBTNode *b,*tb;
CreateTBTNode(b,"A(B(D(,G)),C(E,F))"); printf(" 2叉树:");
DispTBTNode(b); printf("
");
tb=CreaThread(b); printf(" 线索中序序列:");
ThInOrder(tb); printf("
"); return 0;
}