中序、先序、后序的互转

/************************************************************************/
/* 中序先序转后序                                                       */
/************************************************************************/
//读入一段先序和中序遍历的字符串,输出后序遍历的字符串
/*
#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 );
}
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值