1340:【例3-5】扩展二叉树

【题目描述】

由于先序、中序和后序序列中的任一个都不能唯一确定一棵二叉树,所以对二叉树做如下处理,将二叉树的空结点用·补齐,如图所示。我们把这样处理后的二叉树称为原二叉树的扩展二叉树,扩展二叉树的先序和后序序列能唯一确定其二叉树。

现给出扩展二叉树的先序序列,要求输出其中序和后序序列。

【输入】

扩展二叉树的先序序列。

【输出】

输出其中序和后序序列。

【输入样例】

ABD..EF..G..C..

【输出样例】

DBFEGAC
DFGEBCA

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

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

Node *CreateTree(const string &pre, int &index)
{
    if (index < 0 || index >= pre.size() || pre[index] == '.') {
        return NULL;
    } else {
        // cout << pre << "," << in << endl;
        Node *root = new Node;
        root->value = pre[index];
        index += 1;
        root->left = CreateTree(pre, index);
        index += 1;
        root->right = CreateTree(pre, index);
        return root;
    }
}

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

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

string PostOrder(Node *root)
{
    string s;
    if (root != NULL) {
        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;
    int index = 0;
    Node *root = CreateTree(pre, index);
    // cout << PreOrder(root) << endl;
    cout << InOrder(root) << endl;
    cout << PostOrder(root) << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/gaojs/p/14942190.html