zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    CodePlus#4 最短路
    最大子矩阵问题———悬线法
    Luogu P3393 逃离僵尸岛
    SCOI2011 糖果
    关于页面的跳转添加参数(比如id啥的)
    npm 常用命令
    移动开发中的一些基本的思想,和需要注意的细节技巧之处
    Mock模拟后台数据接口--再也不用等后端的API啦
    普及知识
    移动端JD首页H5页面
  • 原文地址:https://www.cnblogs.com/gaojs/p/14942139.html
Copyright © 2011-2022 走看看