由先序遍历和中序遍历序列可唯一还原出二叉树,前提条件是所有节点的关键字无重复。
分析:
设post_order(pre, in)表示先序序列为pre,中序序列为in的二叉树的后序序列。
根据后序序列的定义可知:post_order(pre, in) = 左子树的后序序列+右子树的后序序列+root;
根据先序序列的定义可知:pre = root+左子树的先序序列+右子树的先序序列, 可知root=pre[0];
根据中序序列的定义可知:in = 左子树的中序序列+root+右子树的中序序列;
由于已经知道了root=pre[0],所以我们可以在in中找到root的位置,于是将in序列拆分开来,得到了左子树的中序序列in1和右子树的中序序列in2;
再根据in1或者in2的长度,我们又可以将pre序列拆分开来,得到左子树的先序序列pre1和右子树的先序序列pre2.
综上,可以得到公式:post_order(pre, in) = post_order(pre1, in1)+post_order(pre2, in2)+pre[0];
于是通过递归,我们就可以拼凑出我们所需要的答案。
代码:
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 string post_order(string pre, string in) 7 { 8 size_t len = pre.length(); 9 if(len<=1) return pre; 10 size_t loc = in.find(pre[0]); 11 return post_order(pre.substr(1, loc), in.substr(0, loc))+post_order(pre.substr(loc+1, len-loc), in.substr(loc+1, len-loc))+pre[0]; 12 } 13 14 int main() 15 { 16 string pre, in; 17 while(cin>>pre>>in) cout<<post_order(pre, in)<<endl; 18 return 0; 19 }
题目来源:http://hihocoder.com/problemset/problem/1049