二叉树遍历序列还原(C++语言)

给出二叉树的中序遍历序列和后序遍历序列,编程还原该二叉树。

输入:
  第1行为二叉树的中序遍历序列
  第2行为二叉树的后序遍历序列

输出:
  二叉树的按层遍历序列


样例

输入(1)

badcfeg
bdfgeca

输出(1)

abcdefg

输入(2)

cbdafeg
cbdfgea

输出(2)

adebfgc

输入(3)

edcba
edcba

输出(3)

abcde

输入(4)

bdfgeca
gfedcba

输出(4)

abcdefg

代码

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

struct Node {
    char data;
    Node* left;
    Node* right;
};

// Function to create a new node
Node* NewNode(char data) {
    Node* node = new Node;
    node->data = data;
    node->left = nullptr;
    node->right = nullptr;
    return node;
}

// Function to find the index in the in-order sequence
int Search(const string& in, int start, int end, char value) {
    for (int i = start; i <= end; i++) {
        if (in[i] == value) {
            return i;
        }
    }
    return -1; // Return -1 if not found
}

// Function to build a binary tree from in-order and post-order sequences
Node* BuildTree(const string& in, const string& post, int inStart, int inEnd, int& postIndex) {
    if (inStart > inEnd) {
        return nullptr;
    }
    // Create a new node, and use postIndex as the root position
    Node* node = NewNode(post[postIndex--]);
    if (inStart == inEnd) {
        return node;
    }
    // Find the index of the node in the 'in' sequence
    int inIndex = Search(in, inStart, inEnd, node->data);
    // Recursively build left and right subtrees
    node->right = BuildTree(in, post, inIndex + 1, inEnd, postIndex);
    node->left = BuildTree(in, post, inStart, inIndex - 1, postIndex);
    return node;
}

// Function to print the level order traversal
void PrintLevelOrder(Node* root) {
    if (root == nullptr) return;
    queue<Node*> q;
    q.push(root);
    while (!q.empty()) {
        int nodeCount = q.size();
        while (nodeCount > 0) {
            Node* node = q.front();
            cout << node->data;
            q.pop();
            if (node->left != nullptr)
                q.push(node->left);
            if (node->right != nullptr)
                q.push(node->right);
            nodeCount--;
        }
    }
    cout << endl;
}

int main() {
    string in;
    string post;
    cin >> in >> post;
    int len = in.size();
    int postIndex = len - 1;
    Node* root = BuildTree(in, post, 0, len - 1, postIndex);
    PrintLevelOrder(root);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值