思路
1.前序遍历:root [左子树] [右子树]
2.中序遍历:[左子树] root [右子树]
3.递归,找到每次的子树边界就行。
code
#include <iostream>
#include <algorithm>
using namespace std;
typedef struct Node{
char data;
Node * lc;
Node * rc;
}Node;
const int N = 30;
string pre;
string mid;
Node * buildTree(int pl, int pr, int ml, int mr){
if(pl > pr){ // 递归边界
return NULL;
}
Node* p = new Node();
// cout << p->data << " " ;
int pos = mid.find(pre.at(pl));
int sz = pos - ml;
p->lc = buildTree(pl+1, pl + sz, ml, pos-1);// 左子树
p->rc = buildTree(pl+sz+1, pr, pos+1, mr); // 右子树
p->data = pre.at(pl); // 树根
cout << p->data;
return p;
}
int main(){
while(cin >> pre >> mid){
Node * tree = buildTree(0,pre.length()-1,0,mid.length()-1);
cout << endl;
}
system("pause");
return 0;
}