2020-11-17 中序线索二叉树

博客提及中序线索二叉树,还指出先序与后序线索化尚未实现过,围绕二叉树线索化展开相关内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

中序线索二叉树
先序与后序线索化还没实现过

#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.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值