题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
思想:使用分治法建左右子树。
#include <stdio.h>
#include <stdlib.h>
typedef struct tree
{
int id;
struct tree * lc;
struct tree * rc;
}tree, *p_tree;
p_tree root;
int *pre, *mid;
int creat_tree( int low, int high, p_tree *t, int m_low, int m_high )
{
int i, count = 0, f1, f2;
int flag;
if( high - low != m_high - m_low )
{
return 0;
}
if( low > high ) // 细节
{
return 1;
}
(*t) = ( p_tree )malloc( sizeof( tree ) );
(*t)->id = pre[low];
(*t)->lc = NULL;
(*t)->rc = NULL;
// if( low == high ) // 细节
// {
// return 1;
// }
flag = 0;
for( i = m_low; i <= m_high; i++ )
{
if( mid[i] == pre[low] )
{
flag = 1;
break;
}
else
{
count++;
}
}
if( flag )
{
f1 = creat_tree( low + 1, low + count, &((*t)->lc), m_low, m_low + count - 1 );
if( !f1 )
{
return 0;
}
f2 = creat_tree( low + count + 1, high, &((*t)->rc), m_low + count + 1, m_high );
return f2;
}
else
{
return 0;
}
}
void out_put( p_tree t )
{
if( t )
{
out_put( t->lc );
out_put( t->rc );
printf("%d ", t->id);
}
}
int main()
{
int i, n;
while( scanf("%d", &n) != EOF )
{
pre = ( int* )malloc( sizeof( int ) * n );
mid = ( int* )malloc( sizeof( int ) * n );
for( i = 0; i < n; i++ )
{
scanf("%d", &pre[i]);
}
for( i = 0; i < n; i++ )
{
scanf("%d", &mid[i]);
}
if( creat_tree( 0, n - 1, &root, 0, n - 1 ) )
{
out_put( root );
}
else
{
printf("No");
}
printf("\n");
}
return 0;
}