思路:
1.采用递归的思想建树
2.先序遍历序列的第一个元素始终是当前子树的根;
3.在中序遍历序列中以根节点为中心,前面的是左子树的先序遍历序列,后面的右子树的先序遍历序列;
#include<iostream>
#include<string>
using namespace std;
struct Node
{
char data;
Node* lchild;
Node* rchild;
};
void PreOrder(Node* root)
{
if(root!=NULL)
{
cout<<root->data;
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
void BuildTree(string sPre,string sMid,Node* &root)
{
if(sPre.length()==0||sMid.length()==0) return;
root=new Node;
root->data=sPre[0];
int index=sMid.find(sPre[0]);
BuildTree(sPre.substr(1,index+1),sMid.substr(0,index),root->lchild);
BuildTree(sPre.substr(index+1),sMid.substr(index+1),root->rchild);
}
int main()
{
string s1="abdecfg";
string s2="dbeafcg";
Node* root=NULL;
BuildTree(s1,s2,root);
PreOrder(root);
cout<<endl;
return 0;
}