算法学习(5)----二叉树前序、中序、后序遍历互相转换
代码:
#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:\n"; cout<<"Pre:"<<pre<<endl <<"In:"<<in<<endl <<"Post:"<<post<<endl; cout<<"From InOrder And PreOrder To PostOrder:\n"; BinaryTreeFromInOrderAndPreOrderToPostOrder(in,pre,8); cout<<endl; cout<<"From InOrder And PostOrder To PreOrder:\n"; BinaryTreeFromInOrderAndPostOrderToPreOrder(in,post,8); cout<<endl; return 0; }