文章

2

粉丝

122

获赞

0

访问

10.3k

头像
土办法,建树

#include <iostream>
#include <string>
using namespace std;

struct TNode {
   char data;
   TNode *left, *right;
   TNode() {}
   TNode(char data)
       : data(data), left(nullptr), right(nullptr) {}
};
typedef TNode* Tree;

Tree BuildTree(string pre, string in) {
   if (pre.empty() || in.empty())
      return nullptr;
   TNode* T = new TNode(pre[0]);
   int p = in.find(pre[0]);
   if (p == -1)
      return nullptr;
   T->left = BuildTree(pre.substr(1, p), in.substr(0, p));
   T->right = BuildTree(pre.substr(p + 1), in.substr(p + 1));
   return T;
}

void PostOrder(Tree T, string& post) {
   if (!T)
      return;
   PostOrder(T->left, post);
   PostOrder(T->right, post);
   post += T->data;
}

int main() {
   string pre_order, in_order, post_order("");
   cin >> pre_order >> in_order;
   TNode* T = BuildTree(pre_order, in_order);
   PostOrder(T, post_order);
   cout << post_order << endl;...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发