• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
山不在高,有金则名!
博客园    首页    新随笔    联系   管理    订阅  订阅

1339:【例3-4】求后序遍历

【题目描述】

输入一棵二叉树的先序和中序遍历序列,输出其后序遍历序列。

【输入】

共两行,第一行一个字符串,表示树的先序遍历,第二行一个字符串,表示树的中序遍历。树的结点一律用小写字母表示。

【输出】

一行,表示树的后序遍历序列。

【输入样例】

abdec
dbeac

【输出样例】

debca

#include <bits/stdc++.h>
using namespace std;

struct Node {
    char value;
    Node *left, *right;
};

Node *CreateTree(const string &pre, const string &in)
{
    if (pre.size() <= 0) {
        return nullptr;
    } else {
        // cout << pre << "," << in << endl;
        Node *root = new Node;
        root->value = pre[0];
        int pos = in.find(pre[0]);
        string pre1 = pre.substr(1, pos);
        string in1 = in.substr(0, pos);
        root->left = CreateTree(pre1, in1);
        string pre2 = pre.substr(pos + 1);
        string in2 = in.substr(pos + 1);
        root->right = CreateTree(pre2, in2);
        return root;
    }
}

string PreOrder(Node *root)
{
    string s;
    if (root != nullptr) {
        s.push_back(root->value);
        s += PreOrder(root->left);
        s += PreOrder(root->right);
    }
    return s;
}

string InOrder(Node *root)
{
    string s;
    if (root != nullptr) {
        s += InOrder(root->left);
        s.push_back(root->value);
        s += InOrder(root->right);
    }
    return s;
}

string PostOrder(Node *root)
{
    string s;
    if (root != nullptr) {
        s += PostOrder(root->left);
        s += PostOrder(root->right);
        s.push_back(root->value);
    }
    return s;
}

int main()
{
    // freopen("1.txt", "r", stdin);
    string pre, in, post;
    cin >> pre >> in;
    Node *root = CreateTree(pre, in);
    // cout << PreOrder(root) << endl;
    // cout << InOrder(root) << endl;
    cout << PostOrder(root) << endl;
    return 0;
}

 

posted @ 2021-06-27 21:11  杭州山不高  阅读(228)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3