UVA536 二叉树重建 Tree Recovery

已知先序和中序求后序遍历。通过递归的方法,先序找根节点,中序找左右子树,然后递归,最后输出根节点。

因为后续遍历是 左子树的后续遍历 + 右子树的后续遍历 + 根

题目链接:https://www.luogu.com.cn/problem/UVA536

  1 #include <iostream>
  2 #include <algorithm>
  3 #include <string>
  4 using namespace std;
  5 string preorder, inorder;
  6 void postorder(string pre, string in) {
  7 	if(pre.size() <= 0)
  8 		return;
  9 	int len = 0;
 10 	len = in.find(pre[0]);
 11 	postorder(pre.substr(1, len), in.substr(0, len));
 12 	postorder(pre.substr(len+1), in.substr(len+1));
 13 	cout << pre[0];
 14 }
 15 
 16 
 17 
 18 int main() {
 19 	while(cin >> preorder >> inorder){
 20 		postorder(preorder, inorder);
 21 		cout << endl;
 22 	}
 23 	return 0;
 24 }
追求吾之所爱
原文地址:https://www.cnblogs.com/rstz/p/14391012.html