标签:
这个弄了好久,最主要理解中序遍历各节点的lchild指向左孩子还是前驱
和rchild指向右孩子还是后继,
还有线索化前的初始化和线索好之后的初始化(不知道这么说对不对,毕竟初学),
可以看看小甲鱼的视频,讲解的很不错,
上代码,前序输入就行,看代码自行了解输入规则,
#include<cstdio> #include<cstring> #include<cstdlib> typedef enum { Link,Thread }PointerTag; typedef struct BiThrNode{ char data; struct BiThrNode *lchild,*rchild; PointerTag LTag; PointerTag RTag; }BiThrNode,*BiThrTree; BiThrTree pre; void CreateThrTree(BiThrTree *T){ char c; scanf("%c",&c); if(‘ ‘ == c){ (*T) = NULL; }else{ *T = (BiThrTree)malloc(sizeof(BiThrNode)); (*T)->data = c; (*T)->LTag = Link; (*T)->RTag = Link; CreateThrTree(&(*T)->lchild); CreateThrTree(&(*T)->rchild); } } void InThreading(BiThrTree T){ if(T){ InThreading(T->lchild); if(T->lchild == NULL){ T->LTag = Thread; T->lchild = pre; } if(pre->rchild == NULL){ pre->RTag = Thread; pre->rchild = T; } pre = T; InThreading(T->rchild); } } void InOrderThreading(BiThrTree *p,BiThrTree T){ *p = (BiThrTree)malloc(sizeof(BiThrNode)); (*p)->LTag = Link; (*p)->RTag = Thread; (*p)->rchild = *p; if(!T){ (*p)->lchild = *p; }else{ (*p)->lchild = T; pre = *p; InThreading(T); pre->rchild = *p; pre->RTag = Thread; (*p)->rchild = pre; } } void OnOrderTraverse(BiThrTree T){ BiThrTree p; p = T->lchild; while(p != T){ while(p->LTag == Link){ p = p->lchild; } printf("%c\n",p->data); while(p->RTag == Thread && p->rchild != T){ p = p->rchild; printf("%c\n",p->data); } p = p->rchild; } } int main(){ BiThrTree p,T; CreateThrTree(&T); InOrderThreading(&p,T); OnOrderTraverse(p); // InThreading(T); return 0; }
标签:
原文地址:http://www.cnblogs.com/zhuozhuo/p/5408758.html