树的形状
树的创建
//树的定义
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 endvist(bt root)
{
if (root == NULL)
return;
if (root->lchild != NULL)
{
endvist(root->lchild);
}
if (root->rchild != NULL)
{
endvist(root->rchild);
}
printf("%d ", root->val);
}
//非递归
void non_endvist(bt root)
{
bt a[10];
int top = -1;
while (root || top >= 0)
{
if (root)
{
a[++top] = root;
root->rl = 0;
root = root->lchild;
}
else
{
root = a[top];
if (root->rchild&&root->rchild->rl!=1)
{
root = root->rchild;
}
else
{
root = a[top--];
printf("%d ", root->val);
root->rl = 1;
root = NULL;
}
}
}
}
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); //创建
endvist(root);//递归
printf("\n");
non_endvist(root);//非递归
printf("\n");
}