数据结构--线索二叉树

#include <stdio.h>
#include <stdlib.h>

typedef struct binary_tree
{
    char data;
    struct binary_tree * lc, * rc;
    int ltag, rtag;
}bit;

bit * pre;

void creat(bit * & );
void headnode(bit * & , bit * );
void threading(bit * );
void inorder(bit * );

int main(void)
{
    bit * root, * head;

    creat(root);
    headnode(head, root);
    inorder(head);

    return 0;
}

void inorder(bit * node)
{
    bit * p;

    p = node->lc;//p为根节点 
    while (p != node)
    {
        while (!p->ltag)//如果左子树非空,一直向下找 
            p = p->lc;
        printf("%c ", p->data);

        while (p->rtag && p->rc != node)//如果右子树为空,且不是头结点,找后继 
        {
            p = p->rc;
            printf("%c ", p->data);
        }
        p = p->rc;//右子树不为空,找到右孩子 
    }
}

void threading(bit * node)
{
    if (node)
    {
        threading(node->lc);//左子树递归线索化 

        if (!node->lc)//若node的左子树为空,左子树指针指向前驱 
        {
            node->ltag = 1;
            node->lc = pre;
        }
        else
            node->ltag = 0;

        if (!pre->rc)//若pre的右子树为空,右子树指针指向后继 
        {
            pre->rtag = 1;
            pre->rc = node;
        }
        else
            pre->rtag = 0;

        pre = node;
        threading(node->rc);//右子树递归线索化 
    }
}

void headnode(bit * &head, bit * root)
{
    head = (bit * )malloc(sizeof(bit));
    head->ltag = 0; 
    head->rtag = 1;
    head->rc = head;//头结点的右子树暂时为自身 
    if (root == NULL)
        head->lc = head;
    else
    {
        head->lc = root;//头结点的左子树为根节点 
        pre = head;//前驱为头结点 
        threading(root);
        pre->rc = head;//最后一个节点的后继是头结点 
        pre->rtag = 1;
        head->rc = pre;//头结点的右孩子是最后一个节点 
    }
}

void creat(bit * &node)
{
    char ch;

    scanf("%c", &ch);

    if (ch == '#')
        node = NULL;
    else
    {
        node = (bit * )malloc(sizeof(bit));
        node->data = ch;
        creat(node->lc);
        creat(node->rc);
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值