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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章