线索化二叉树

线索化二叉树

#include <iostream>
using namespace std;

typedef char ElemType;
#define END '#' //用‘#’表示为空

typedef enum{LINK = 0, THREAD = 1} Pointertag;

typedef struct BiThrNode
{
    ElemType data;
    BiThrTree *leftchild;
    BiThrTree *rightchild;
    BiThrTree *parent;
    Pointer Ltag, Rtag;
}BiThrNode, *BinaryThreadTree;

BiThrNode *_Buynode()
{
    BiThrNode *p = (BiThrNode *)malloc(sizeof(BiThrNode));

    if ( p == NULL) exit(0);

    return p;
}

//先序遍历建立二叉树
BiThrNode *CreateTree(ElemType *&str)
{
    BiThrNode *s = NULL;
    while (*str != END)
    {
        s = _Buynode();
        s->data = *str;
        S->Ltag = s->Rtag = LINK;
        s->leftchild = CreateTree(++str);
        s->righrchild = CreateTree(++str);
    }

    return s;
}

//中序遍历建立线索化
void Make(BiThrTree *p, BiThrTree *&ptr)
{
    if (p != NULL)
    {
        Make(p->leftchild, ptr);
        if (p->leftchild == NULL)
        {
            p->leftchild = ptr;
            p->Ltag = THREAD;
        }

        if(ptr != NULL && ptr->rightchild == NULL)
        {
            ptr->rightchild = p;
            ptr->Rtag == THREAD;
        }

        ptr = p; 
        Make(p->righrchild, ptr);//将其右子树遍历
    }
}

void MakeThread(BiThrNode *p)
{
    if (p = NULL) return;

    BiThrNode *ptr = NULL;
    Make(p, ptr);
    ptr->rightchild = NULL;
    ptr->Rtag = THREAD;             
}

BiThrNode *First(BiThNode *ptr)
{
    if (ptr == NULL) return NULL;

    while(ptr != NULL && ptr->Ltag != THREAD)
    {
        ptr = ptr->leftchild;
    } 

    return ptr;
}

BiThrNode *Next(BiThrNode *ptr)
{
    if (ptr == NULL) return NULL;

    if (ptr->Rtag == THREAD)
    {
        return ptr->rightchild;
    }   
    else
    {
        First(p->rightchild);
    }
}

void NiceInOrder(BiThrNode *ptr)
{
    for (BiThrNode *p = Frist(ptr); p != NULL; p = Next(p))
    {
        cout << p->data << " ";
    }

    cout << endl;
}

BiThrNode *Last(BiThrNode *ptr)
{
    if (ptr == NULL) return NULL;

    while (ptr != NULL && ptr->Rtag != THREAD)
    {
        ptr = ptr->rightchild;//
    }

    return ptr;
}

BiThrNode *Prev(BitThrNode *ptr)
{
    if (ptr = NULL) return NULL;

    if (ptr->Ltag == Thread)//左子树为空
    {
        return ptr->leftchild;
    }
    else //有左子树,找出左子树的最后遍历的一个节点
    {
        return Last(ptr->leftchild);
    }
}

void ResNiceInOrder(BiThrNode *ptr)
{
    for (BiThrNode *p = Last(ptr); p != NULL; p = Prev(p))
    {
        cout << p->data << " ";
    }

    cout << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值