由先序遍历和中序遍历序列可唯一还原出二叉树,前提条件是所有节点的关键字无重复。
题目来源:http://hihocoder.com/problemset/problem/1049
代码:
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 void post_order(string pre, string in) 7 { 8 size_t len = pre.length(); 9 if(len) 10 { 11 if(len==1){cout<<pre; return;} 12 size_t loc = in.find(pre[0]); 13 post_order(pre.substr(1, loc), in.substr(0, loc)); 14 post_order(pre.substr(loc+1, len-loc), in.substr(loc+1, len-loc)); 15 cout<<pre[0]; 16 } 17 } 18 19 int main() 20 { 21 string pre, in; 22 while(cin>>pre>>in) post_order(pre, in); 23 cout<<endl; 24 return 0; 25 }
原文:http://www.cnblogs.com/pczhou/p/4295692.html