中序线索二叉树
先序与后序线索化还没实现过
#include<iostream>
#include<stack>
using namespace std;
#define TElemType double
typedef enum{Link,Thread} PointerTag;
typedef struct BiThrNode
{
TElemType data;
struct BiThrNode* lchild,* rchild;
PointerTag LTag,RTag;
bool flag;//为了非递归后序遍历
}BiThrNode,* BiThrTree;
void Creat_BiTree(BiThrTree& T)//创建二叉树
{
TElemType num;
if(cin>>num){
T=new BiThrNode;
if(!T) exit(-2);
T->data=num;
T->LTag=T->RTag=Link;//初始情况:将LTag、RTag全都设置为Link
Creat_BiTree(T->lchild);
Creat_BiTree(T->rchild);
}
else
T=nullptr;
if(!cin){
cin.clear();
cin.sync();
}
}
void PosOrderUsingStack(BiThrTree T)//非递归后序打印二叉树
{
stack<BiThrTree> S;
BiThrTree p=T;
while(p||!S.empty()){
while(p){
p->flag=true;
S.push(p);
p=p->lchild;
}
while(!S.empty()&&!S.top()->flag){
cout<<S.top()->data<<endl;
S.pop();
}
if(!S.empty()){
p=S.top();
p->flag=false;
p=p->rchild;
}
}
}
void InThreading(BiThrTree p,BiThrTree& pre)//利用递归完成线索化
//bug:pre前未加& 原因:未找到,个人感觉应该是函数递归时出现的问题
{
if(p){
InThreading(p->lchild,pre);
if(!p->lchild){p->LTag=Thread;p->lchild=pre;}
if(!pre->rchild){pre->RTag=Thread;pre->rchild=p;}
pre=p;
InThreading(p->rchild,pre);
}
}
bool InOrderThreading(BiThrTree& Thrt,BiThrTree T)//将二叉树线索化
{
Thrt=new BiThrNode;
if(!Thrt) exit(-2);
Thrt->LTag=Link;
Thrt->RTag=Thread;Thrt->rchild=Thrt;
if(!T) Thrt->lchild=Thrt;
else{
Thrt->lchild=T;
BiThrTree pre=Thrt;
InThreading(T,pre);
pre->RTag=Thread;pre->rchild=Thrt;
Thrt->rchild=pre;
}
cout<<"中序线索化完成\n";
return true;
}
void InOrderThrTraverse(BiThrTree T)//遍历线索二叉树
{
BiThrTree p=T->lchild;
while(p!=T){
while(p->LTag==Link) p=p->lchild;
cout<<p->data<<endl;
while(p->RTag==Thread&&p->rchild!=T){
p=p->rchild;
cout<<p->data<<endl;
}
p=p->rchild;
}
}
int main()
{
BiThrTree T;
Creat_BiTree(T);
PosOrderUsingStack(T);
BiThrTree Thrt;
InOrderThreading(Thrt,T);
InOrderThrTraverse(Thrt);//哈哈哈,我的我的... InOrderThrTrverse(T) 可真有你的
return 0;
}
1.1
2.2
4.4
@
6.6
@
@
5.5
7.7
@
@
@
3.3
@
@
6.6
4.4
7.7
5.5
2.2
3.3
1.1
中序线索化完成
4.4
6.6
2.2
7.7
5.5
1.1
3.3
Process returned 0 (0x0) execution time : 13.290 s
Press any key to continue.