ACM:已知二叉树的前序,中序,求后序
思路:
由前序得出根节点,在中序中,根节点左边为左子树,根节点右边为右子树,递归遍历
#include <iostream>
using namespace std;
typedef struct _BTNode
{
char data;
_BTNode *lchild,*rchild;
} BTNode;
char *Predata,*Indata;
void build(int preLeft,int preRight,int inLeft,int inRight)//四个参数分别为前序、中序的起点和终点
{
int root;
for(root=inLeft;root<=inRight;root++)
{
if(Predata[preLeft]==Indata[root]) //找到根节点
break;
}
int LeftSize=root-inLeft;//计算左子树的规模和右子树规模
int RightSize=inRight-root;
if(LeftSize>0)//递归左子树
{
build(preLeft+1,preLeft+LeftSize,inLeft,root-1);
}
if(RightSize>0)//递归右子树
{
build(preLeft+LeftSize+1,preRight,root+1,inRight);
}
cout<<Indata[root]<<" ";//输出根
}
int main(int argc, char *argv[])
{
Predata="DBACEGF";//前序
Indata="ABCDEFG";//中序
build(0,strlen(Predata)-1,0,strlen(Indata)-1);
cout<<endl;
return 0;
}