POJ 2255 Tree Recovery 二叉树遍历

题意:给出一棵二叉树的先序遍历和中序遍历,输出它的后序遍历。
题解:

#include <iostream>
using namespace std;

char preorder[30], inorder[30], postorder[30];
int len;

void travel ( int pStart, int pEnd, int inStart, int inEnd )
{
	if ( pStart > pEnd ) return;
	postorder[--len] = preorder[pStart];
	if ( pStart == pEnd ) return;
	
	int i;
	for ( i = inStart; i <= inEnd; i++ )
		if ( inorder[i] == preorder[pStart] )
			break;
	travel ( pStart + i - inStart + 1, pEnd, i + 1, inEnd );
	travel ( pStart + 1, pStart + i - inStart, inStart, i - 1 );
}

int main()
{
	while ( cin >> preorder >> inorder )
	{
		len = strlen(preorder);
		memset(postorder,0,sizeof(postorder));
		postorder[len] = '\0';
		travel ( 0, len - 1, 0, len - 1 );
		cout << postorder << endl;
	}
	return 0;
}


你可能感兴趣的:(tree)