PTA: Construct a binary tree in post-order and in-order

Constructing a binary tree in post-order and in-order

topic

This question requires constructing a binary tree (the number of nodes in the tree does not exceed 10) using the post-order sequence and the in-order sequence, and output its pre-order sequence.

Input format

Enter the number of elements in the first line.

Enter the sequence in the second line, separated by spaces.

Enter the in-order sequence in the third line, separated by spaces.

Output format

Output the preorder sequence of this binary tree, separated by spaces, with a space at the end.

Input examples (and their corresponding binary trees)

5
20 40 50 30 10
20 10 40 30 50
## 输出样例
10 20 30 40 50 

code

#include <iostream>
#include <vector>
#include <unordered_map>

class TreeNode {
    
    
public:
    int val;
    TreeNode* left;
    TreeNode* right;

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {
    
    }
};

TreeNode* buildTree(std::vector<int>& inorder, std::vector<int>& postorder, int inStart, int inEnd, int postStart, int postEnd, std::unordered_map<int, int>& indexMap) {
    
    
    if (inStart > inEnd || postStart > postEnd) {
    
    
        return nullptr;
    }

    int rootVal = postorder[postEnd];
    TreeNode* root = new TreeNode(rootVal);
    int rootIndex = indexMap[rootVal];

    int leftSubtreeSize = rootIndex - inStart;

    root->left = buildTree(inorder, postorder, inStart, rootIndex - 1, postStart, postStart + leftSubtreeSize - 1, indexMap);
    root->right = buildTree(inorder, postorder, rootIndex + 1, inEnd, postStart + leftSubtreeSize, postEnd - 1, indexMap);

    return root;
}

void preorderTraversal(TreeNode* root) {
    
    
    if (root == nullptr) {
    
    
        return;
    }

    std::cout << root->val << " ";
    preorderTraversal(root->left);
    preorderTraversal(root->right);
}

int main() {
    
    
    int n;
    std::cin >> n;

    std::vector<int> postorder(n);
    std::vector<int> inorder(n);

    for (int i = 0; i < n; ++i) {
    
    
        std::cin >> postorder[i];
    }

    for (int i = 0; i < n; ++i) {
    
    
        std::cin >> inorder[i];
    }

    std::unordered_map<int, int> indexMap;
    for (int i = 0; i < n; ++i) {
    
    
        indexMap[inorder[i]] = i;
    }

    TreeNode* root = buildTree(inorder, postorder, 0, n - 1, 0, n - 1, indexMap);
    preorderTraversal(root);
    std::cout << std::endl;

    return 0;
}

Guess you like

Origin blog.csdn.net/m0_74195626/article/details/134121300