已知二叉樹前序序列和中序序列遞歸創建二叉樹
#include<bits/stdc++.h>
using namespace std;
typedef struct Node{
char data;
struct Node *lchild;
struct Node *rchild;
}Node;
typedef Node* node;
Node* create_first(string pre,string middle,int n)
{
Node *root;
if(n<=0) return NULL;
else{
root =new Node;int pos=0;
for(int i=0;i<n;i++){
if(middle[i]==pre[0]) {
pos=i;break;
}
}
root->data=middle[pos];
string s1=pre.substr(1,pos);
string s2=middle.substr(0,pos);
root->lchild=create_first(s1,s2,pos);
string s3=pre.substr(pos+1,n-pos-1);
string s4=middle.substr(pos+1,n-pos-1);
root->rchild=create_first(s3,s4,n-pos-1);
return root;
}
}
int getnode(Node *T)
{
if(T==NULL) return 0;
else{
return 1+getnode(T->lchild)+getnode(T->rchild);
}
}
int main()
{
string pre,middle;
cin>>pre;
cin>>middle;
node head=create_first(pre,middle,pre.length());
cout<<getnode(head);
}