這題要是做數(shù)據(jù)結(jié)構(gòu)的練習(xí)題挺好的
就是給出前序和中序序列 要求后序序列
在先序序列中,第一個(gè)元素為二叉樹(shù)的根,之后為它的左子樹(shù)和右子樹(shù)的先序序列;在中序序列中,先是左子樹(shù)的中序序列,然后是根,再就是右子樹(shù)的中序序列。由此就可以遞歸的建立起這棵二叉樹(shù)了。
遞歸有時(shí)真的很美。。。
Node* create(const string& pres,const string& ins)
{
??? Node* root;
??? if(pres.length()>0)
??? {
??? ??? root=new Node;
??? ??? root->data=pres[0];
??? ??? int index=ins.find(root->data);
??? ??? root->left=create(pres.substr(1,index),ins.substr(0,index));
??? ??? root->right=create(pres.substr(index+1),ins.substr(index+1));
??? }
??? else root=NULL;
??? return root;
}