树的形状
树的创建(线索化版)
#include<stdio.h>
#include<malloc.h>
#include<vector>
typedef struct bitree
{
int val;
struct bitree* lchild;
struct bitree* rchild;
int rl;
int ltag = 0;
int rtag = 0;
}BT, * bt;
bt thread_creattree(int* a, int* b, int a1, int a2, int b1, int b2)
{
bt root = (bt)malloc(sizeof(BT));
root->val = a[a1];
int llen = 0, rlen = 0;
int i = 0;
for (; b[i] != a[a1]; i++);
llen = i - b1;
rlen = b2 - i;
if (llen)
{
root->lchild = thread_creattree(a, b, a1 + 1, a1 + llen, b1, b1 + llen - 1);
root->ltag = 0;
}
else
{
root->lchild = NULL;
root->ltag = 0;
}
if (rlen)
{
root->rchild = thread_creattree(a, b, a2 - rlen + 1, a2, b2 - rlen + 1, b2);
root->rtag = 0;
}
else
{
root->rchild = NULL;
root->rtag = 0;
}
return root;
}
树线索化
void prethread(bt& root, bt& pre)
{
if (root != NULL && root->rl != 1)
{
root->rl = 1;
if (root->lchild == NULL)
{
root->lchild = pre;
root->ltag = 1;
}
if (pre != NULL && pre->rchild == NULL)
{
pre->rchild = root;
pre->rtag = 1;
}
pre = root;
prethread(root->lchild, pre);
prethread(root->rchild, pre);
}
}
void preclue(bt& root)
{
if (root != NULL)
{
bt pre = NULL;
prethread(root, pre);
pre->rchild = NULL;
pre->rtag = 1;
}
}
线索化遍历
bt prefirstnode(bt root)
{
if (root->ltag == 1)
root = root->rchild;
else root = root->lchild;
return root;
}
bt prenextnode(bt root)
{
if (root->rtag == 1) return root->rchild;
else
{
return prefirstnode(root);
}
}
void preorder(bt root)
{
for (bt first = root; first != NULL; first = prenextnode(first))
{
printf("%d ", first->val);
}
}
main函数
int main()
{
int a[10] = { 1,2,4,7,10,3,5,8,9,6 };
int b[10] = { 10,7,4,2,1,8,5,9,3,6 };
int a1 = 0;
int a2 = sizeof(a) / sizeof(a[0]);
int b1 = 0;
int b2 = sizeof(b) / sizeof(b[0]);
bt root = NULL;
root = thread_creattree(a, b, a1, a2 - 1, b1, b2 - 1);
preclue(root);
preorder(root);
printf("\n");
}