标签:
#include <iostream> using namespace std; typedef struct Tree { char data; int lTag, rTag; struct Tree *lchild, *rchild; }Tree; void firstCreateTree(Tree* &T) { char ch; cin >> ch; if (‘#‘ == ch) T= NULL; else { T = new Tree; T->data=ch; firstCreateTree(T->lchild); firstCreateTree(T->rchild); } } Tree* pre; void InThreading(Tree* &T) {//树线索化 if (T) { InThreading(T->lchild); if (!T->lchild) { T->lTag = 1; T->lchild = pre; } else T->lTag = 0; if (!pre->rchild) { pre->rTag = 1;//这个很关键,补回去前面的rTag pre->rchild = T; } else T->rTag = 0;//不是pre,而是T pre = T; InThreading(T->rchild); } } void InOrderThreading(Tree* &T, Tree* &Thrt) {//整棵树线索化 Thrt = new Tree; // Thrt->lchild = T; Thrt->rTag = 1; Thrt->rchild = Thrt; Thrt->lTag = 0; if (!T)Thrt->lchild = Thrt; else { Thrt->lchild = T; pre = Thrt; InThreading(T); pre->rchild = Thrt; pre->rTag = 1; Thrt->rchild = pre; } } void InorderTraverse(Tree* T) { Tree *p = T->lchild; for (; p != T;) { for (; p->lTag == 0;)p = p->lchild;//往下搞到1,也就是没有左孩子 cout << p->data; //输出最左的一个孩子 for (; p->rTag == 1 && p->rchild != T;)//看右孩子是不是为1,也就是空 { p = p->rchild; //空的话跟线索回到上一个并输出 cout << p->data; } p = p->rchild; //不空的话就到了右孩子那里,看起来和上面的相同,其实是不一样的 } } int main() { Tree *T,*Thrt; firstCreateTree(T); InOrderThreading(T,Thrt); // cout << Thrt->rTag << endl;曾经不会这个点 InorderTraverse(Thrt); }
标签:
原文地址:http://www.cnblogs.com/vhyc/p/5502664.html