这种方法简便地利用前序遍历和后续遍历就得到了一颗完整的树,虽然原理还不太清楚,但是感觉是利用了s2中lo,与hi,当不符合条件的时候才转向右子树。另外利用队列进行广度优先遍历也是一个亮点。
#include <iostream>
#include <string>
#include <queue>
using namespace std;
int index;
string s1,s2;
int len;
struct Node {
char ch;
Node* l;
Node* r;
Node(char t=' '):ch(t),l(NULL),r(NULL){}
};
void rebuild(Node* &root,int lo, int hi) {
if (lo>hi||index>=len) return;
else {
root=new Node(s1[index]);
int d = s2.find(s1[index++]);
rebuild(root->l,lo,d-1);
rebuild(root->r,d+1,hi);
}
}
void bfs(Node* root) {
if(!root) return;
queue<Node*> Q;
Q.push(root);
while (!Q.empty()) {
Node* tmp = Q.front();
Q.pop();
cout<<tmp->ch;
if(tmp->l) Q.push(tmp->l);
if(tmp->r) Q.push(tmp->r);
}
cout<<endl;
}
int main() {
int t;
cin>>t;
while (t--) {
cin>>s1>>s2;
len = s1.size();
index = 0;
Node* root=new Node();
rebuild(root,0,len-1);
bfs(root);
}
}
393

被折叠的 条评论
为什么被折叠?



