当前位置: 代码迷 >> 综合 >> UVa 536 Tree Recovery
  详细解决方案

UVa 536 Tree Recovery

热度:75   发布时间:2023-12-24 07:45:10.0

思路分析:

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

题解:

#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;
}


  相关解决方案