本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。
输入格式:
第一行给出正整数N(≤30),是树中结点的个数。随后两行,每行给出N个整数,分别对应后序遍历和中序遍历结果,数字间以空格分隔。题目保证输入正确对应一棵二叉树。
输出格式:
在一行中输出Preorder:以及该树的先序遍历结果。数字间有1个空格,行末不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
Preorder: 4 1 3 2 6 5 7
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node* lchild;
struct node* rchild;
}BTNode, * BiTree;
void ReBiTree(int post[], int inod[], int n, BiTree* bt)
{
if (n <= 0)
{
(*bt) = NULL;
return;
}
else
{
PreInOd(post, 0, n-1, inod, 0, n-1, bt);
}
}
void PreInOd(int post[], int i, int j, int inod[], int k, int h, BiTree* bt)
{
(*bt) = (BTNode*)malloc(sizeof(BTNode));
(*bt)->data = post[j];
int m = k;
while (inod[m] != post[j])
{
m++;
}
if (m == k)
{
(*bt)->lchild = NULL;
}
else
{
PreInOd(post, i , i + m - k-1, inod, k, m - 1, &((*bt)->lchild));
}
if (m == h)
{
(*bt)->rchild = NULL;
}
else
{
PreInOd(post, i + m - k , j-1, inod, m + 1, h, &((*bt)->rchild));
}
}
int GetHeight(BiTree bt)
{
int left = 0, right = 0;
if (bt == NULL)
{
return 0;
}
else
{
left = GetHeight(bt->lchild);
right = GetHeight(bt->rchild);
if (left > right)
{
return (left + 1);
}
else
{
return (right + 1);
}
}
}
int flag=1;
void PreOrder(BiTree bt)
{
if (bt==NULL)
return;
if (flag==1)
{
printf("%d",bt->data);
flag=0;
}
else
{
printf(" %d",bt->data);
}
PreOrder(bt->lchild);
PreOrder(bt->rchild);
}
int main()
{
int n,i;
int post[30], inod[30]; //在此将数组长度设为30 可根据需要调整
printf("Please input n\n");
scanf("%d", &n);
printf("Please input the post\n");
for (i=0;i<n;i++)
{
scanf(" %d",&post[i]);
}
printf("Please input the inod\n");
for (i=0;i<n;i++)
{
scanf(" %d",&inod[i]);
}
BiTree bt;
ReBiTree(post, inod, n, &bt);
printf("%d\n", GetHeight(bt)); //计算树的高度
PreOrder(bt);
return 0;
}