/************************************************************************/
/* 中序先序转后序 */
/************************************************************************/
//读入一段先序和中序遍历的字符串,输出后序遍历的字符串
/*
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int find( char pre[] , char ino[] , int start , int end ){
int i , j;
for( i = 0 ; i < strlen( pre ) ; i ++ ) {//从先序里面找一个字符
for( j = start ; j <= end ; j ++ ) {
if( ino[ j ] == pre[ i ] ) {
return j;//返回中序里面那个分割位置
}
}
}
}
void converse( char pre[] , char ino[] , int start , int end ) {
int mid = find( pre , ino , start , end );
if( mid > start ) converse( pre , ino , start , mid - 1 );
if( mid < end ) converse( pre , ino , mid + 1 , end );
printf( "%c" , ino[ mid ] );
}
int main( ) {
char pre[ 30 ]; //先序遍历的字符串
char ino[ 30 ]; //中序遍历的字符串
scanf( "%s" , pre );
scanf( "%s" , ino );
converse( pre , ino , 0 , strlen( pre ) - 1 );
}
//1245367
//4251637
*/
/************************************************************************/
/* 后序、中序转先序 */
/************************************************************************/
//类似于上面的代码,关键是要找分割点mid
/*
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int find( char pos[] , char ino[] , int start , int end ){
int i , j;
for( i = strlen( pos ) - 1 ; i >= 1 ; i -- ) {//从先序里面找一个字符
for( j = start ; j <= end ; j ++ ) {
if( ino[ j ] == pos[ i ] ) {
printf( "%c" , ino[ j ] );
return j;//返回中序里面那个分割位置
}
}
}
}
void converse( char pos[] , char ino[] , int start , int end ) {
int mid = find( pos , ino , start , end );
if( mid > start ) converse( pos , ino , start , mid - 1 );
if( mid < end ) converse( pos , ino , mid + 1 , end );
}
int main( ) {
char pos[ 30 ]; //先序遍历的字符串
char ino[ 30 ]; //中序遍历的字符串
scanf( "%s" , pos );
scanf( "%s" , ino );
converse( pos , ino , 0 , strlen( pos ) - 1 );
}
*/
中序、先序、后序的互转
最新推荐文章于 2024-07-28 17:42:24 发布