PAT Grade A Zhenti 1020 Tree Traversal

Topic

Insert picture description here

answer

  1. According to the pre-order/post-order and middle-order traversal results, we can all restore this binary tree, because the pre-order (left and right root), middle-order (left root and right), post-order (left and right root), we are based on the location of the root of the tree , We can get the left and right sons of the tree. As long as we recursively process, we can restore the entire tree. Pay attention to the boundary problem of the interval. You can directly list the numbers to determine it, so it is not easy to make mistakes.
  1. When the tree is completed, we only need to perform the BFS from the root node to achieve the layer sequence traversal

Code

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<unordered_map>
#include<queue>

using namespace std;
const int N = 35;

int n, x;
//前序/中序/后序 preorder/inorder/postorder
vector<int> inorder, postorder;
unordered_map<int, int> mp;

struct TreeNode {
    
    
    int val;
    TreeNode *left;
    TreeNode *right;

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


TreeNode *dfs(int il, int ir, int pl, int pr) {
    
    
    if (pl > pr) return NULL;
    int k = mp[postorder[pr]];  //中序遍历的根节点下标
    TreeNode *root = new TreeNode(inorder[k]);
    root->left = dfs(il, k - 1, pl, pl + k - il - 1);
    root->right = dfs(k + 1, ir, pl + k - il, pr - 1);
    return root;
}


TreeNode *buildTree() {
    
    
    for (int i = 0; i < n; i++) {
    
    
        mp[inorder[i]] = i;
    }
    return dfs(0, n - 1, 0, n - 1);
}

int main() {
    
    

    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    cin >> n;
    for (int i = 0; i < n; i++) {
    
    
        cin >> x;
        postorder.push_back(x);
    }
    for (int i = 0; i < n; i++) {
    
    
        cin >> x;
        inorder.push_back(x);
    }

    TreeNode *root = buildTree();  //建树,返回根节点

    //款搜进行层序遍历
    queue<TreeNode> q;
    q.push(*root);
    vector<int> res;
    while (q.size()) {
    
    
        auto t = q.front();
        q.pop();
        res.push_back(t.val);
        if (t.left != nullptr) q.push(*t.left);
        if (t.right != nullptr) q.push(*t.right);
    }

    for (int i = 0; i < n; i++) {
    
    
        if (i != n - 1) {
    
    
            cout << res[i] << " ";
        } else {
    
    
            cout << res[i] << endl;
        }
    }

    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/115112221