代码:
#include <iostream> using namespace std; void BinaryTreeFromInOrderAndPreOrderToPostOrder(char InOrder[],char PreOrder[],int length) { if(length<=0){ return; } int rootIndex=0; for(;rootIndex<length;rootIndex++){ if(InOrder[rootIndex]==PreOrder[0]) break; } BinaryTreeFromInOrderAndPreOrderToPostOrder(InOrder,PreOrder+1,rootIndex); BinaryTreeFromInOrderAndPreOrderToPostOrder(InOrder+rootIndex+1,PreOrder+rootIndex+1,length-rootIndex-1); cout<<PreOrder[0]; } void BinaryTreeFromInOrderAndPostOrderToPreOrder(char InOrder[],char PostOrder[],int length) { if(length<=0){ return ; } int rootIndex=0; for(;rootIndex<length;rootIndex++){ if(InOrder[rootIndex]==PostOrder[length-1]) break; } cout<<PostOrder[length-1]; BinaryTreeFromInOrderAndPostOrderToPreOrder(InOrder,PostOrder,rootIndex); BinaryTreeFromInOrderAndPostOrderToPreOrder(InOrder+rootIndex+1,PostOrder+rootIndex,length-rootIndex-1); } int main(int argc,char* argv[]) { char pre[]="GDAFEMHZ"; char in[]="ADEFGHMZ"; char post[]="AEFDHZMG"; cout<<"The original strings are: "; cout<<"Pre:"<<pre<<endl <<"In:"<<in<<endl <<"Post:"<<post<<endl; cout<<"From InOrder And PreOrder To PostOrder: "; BinaryTreeFromInOrderAndPreOrderToPostOrder(in,pre,8); cout<<endl; cout<<"From InOrder And PostOrder To PreOrder: "; BinaryTreeFromInOrderAndPostOrderToPreOrder(in,post,8); cout<<endl; return 0; }