树形状
树的创建
typedef struct bitree
{
int val;
struct bitree* lchild;
struct bitree* rchild;
int rl;
}BT, * bt;
bt 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=creattree( a, b, a1 + 1, a1 + llen, b1, b1 + llen - 1);
}
else
{
root->lchild = NULL;
}
if (rlen)
{
root->rchild=creattree( a, b, a2 - rlen + 1, a2, b2 - rlen + 1, b2);
}
else
{
root->rchild = NULL;
}
return root;
}
树的中序遍历
//递归
void midvist(bt root)
{
if (root == NULL)
return;
if (root->lchild != NULL)
{
midvist(root->lchild);
}
printf("%d ", root->val);
if (root->rchild != NULL)
{
midvist(root->rchild);
}
}
//非递归
void non_midvist(bt root)
{
bt a[10];
int top = -1;
while (root || top >= 0)
{
if (root)
{
a[++top] = root;
root = root->lchild;
}
else
{
root = a[top--];
printf("%d ", root->val);
root = root->rchild;
}
}
}
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 = 9;
int b1 = 0;
int b2 = 9;
bt root=NULL;
root=creattree(a, b, a1, a2, b1, b2);
midvist(root);
printf("\n");
non_midvist(root);
printf("\n");
}