#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);
}
}
数据结构--线索二叉树
最新推荐文章于 2023-03-31 23:12:31 发布