中序线索二叉树
各位大佬好,我尝试写了一个线索操作,我把我想到的情况都给进行测试了,我怕还有一些特殊的情况
没有测试到,如果大佬发现了请在评论里面说一下。
顺便说一下,电脑测试的不太方便,我用本子上测试的
- 结构体
struct mk // 节点操作
{
int data;// 数据域
struct mk *left_next;// 左子节点
struct mk *right_next;// 右子节点
int left, right;// 判断 左右是线索还是节点 0为节点 1为线索
};
- 主函数
int xian(struct mk *a, struct mk **p, struct mk **t, int *kai);// 线索化函数
void establish(struct mk *a, int max, int *t);// 创建树 创建的是平衡二叉树
void bian(struct mk *a);// 遍历函数
int main(void)
{
struct mk *a = (struct mk*)malloc(sizeof(struct mk));
struct mk *b = (struct mk*)malloc(sizeof(struct mk));
struct mk *c = (struct mk*)malloc(sizeof(struct mk));
int max = 3;//数的层数
int *t = (int *)malloc(sizeof(int)); // 计数器
*t = 1;
establish(a, max, t);// 创建一个平衡二叉树 a为根节点 max为树成数 t记录节点个数顺便赋值
*t = 0;
xian(a, &c, &b, t);// 线索化二叉树 t为开关 c和b是中间储存
bian(a);// 遍历中序二叉线索树
printf("ha");
}
- 线索化函数
int xian(struct mk *a, struct mk **p, struct mk **t, int *kai)
{
int dian = 0;
if (a != NULL)
{
if (a->left_next == NULL)
{
if (*kai == 0)
{
*p = a;
a->left = 1;
*kai = 1;
}
else
{
a->left = 1;
a->left_next = *p;
*p = a;
}
}
else
{
a->left = 0;
dian = xian(a->left_next, p, t, kai);
}
if (dian == 1)
{
(*t)->right_next = a;
}
*p = a;
if (a->right_next == NULL)
{
*t = a;
a->right = 1;
return 1;
}
else
{
a->right = 0;
xian(a->right_next, p, t, kai);
}
}
}
- 遍历函数
void bian(struct mk *a)
{
struct mk *zong=a;
while (1)
{
if (a->left_next == NULL)
{
//printf("%d ", a->data);
break;
}
a = a->left_next;
}
while (a->right_next != NULL)
{
if (a->left == 0 && zong->right_next!=a)
{
//printf("%d ", a->data);
a = a->left_next;
}
else if (a->right == 1)
{
printf("%d ", a->data);
zong = a;
a = a->right_next;
}
else
{
printf("%d ", a->data);
a = a->right_next;
}
}
printf("%d", a->data);
}