UVa 536 Tree Recovery

来源:互联网 发布:ubuntu内核 编辑:程序博客网 时间:2024/06/05 08:59

思路分析:

简单的根据先序和中序序列重建二叉树,再后序遍历输出即可。

题解:

#include <cstdio>#include <iostream>#include <string>using namespace std;struct Node{char data;Node *left, *right;};string str, pre, in;Node* create(int pl, int pr, int inl, int inr){if(pl > pr) return NULL;Node* root = new Node;root->data = pre[pl];int k;for(int i = inl; i <= inr; i++){if(in[i] == pre[pl]){k = i;break;}}int leftlen = k - inl;root->left = create(pl+1, pl+leftlen, inl, k-1);root->right = create(pl+leftlen+1, pr, k+1, inr);return root;}void postorder(Node* root){if(root != NULL){postorder(root->left);postorder(root->right);printf("%c", root->data);}}int main(){while(getline(cin, str) && str != ""){int k = -1;for(int i = 0; i < str.length(); i++){if(str[i] == ' '){k = i;break;}}pre = str.substr(0, k);in = str.substr(k+1, str.length());int n = pre.length();Node* root = create(0, n-1, 0, n-1);postorder(root);printf("\n");}return 0;}