L2-006 tree traversal (25 points)
Given a binary tree's post order traversal and middle order traversal, please output the sequence of its sequence traversal. It is assumed that all key values are positive integers that are not equal to each other.
Input format:
Input the first line to give a positive integer N (< 30), which is the number of nodes in the binary tree. The second line gives the sequence of traversal. In the third line, we give the order traversal sequence. Numbers are separated by spaces.
Output format:
Output the sequence traversal sequence of the tree in a row. Numbers are separated by one space, and there must be no extra space at the beginning and end of the line.
Input example:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Output example:
4 1 6 3 5 7 2
Title Solution
Recursive tree building
Code
#include <iostream> #include <vector> #include <queue> using namespace std; struct BinTree { int val; BinTree *left, *right; }; vector<int> post_order, in_order; int n; BinTree* BuildTree(BinTree *root, int l, int r, int pl, int pr) { if(l > r || pl > pr) return nullptr; root = new BinTree; root->val = post_order[pr]; root->left = root->right = nullptr; int ri = -1; for(int i=l;i<=r;i++) { if(in_order[i] == root->val) { ri = i; break; } } int mid = pl-1; for(int i=l;i<ri;i++) { for(int j=pl;j<pr;j++) { if(in_order[i] == post_order[j]) { if(j > mid) mid = j; } } } root->left = BuildTree(root->left, l, ri-1, pl, mid); root->right = BuildTree(root->right, ri+1, r, mid+1, pr-1); return root; } void layer_order(BinTree *root) { queue<BinTree*> q; vector<int> ans; if(root == nullptr) return ; q.push(root); while(!q.empty()) { BinTree *node = q.front();q.pop(); ans.push_back(node->val); if(node->left) q.push(node->left); if(node->right) q.push(node->right); } for(int i=0;i<ans.size();i++) { if(i!=0) cout << " "; cout << ans[i]; } } int main() { cin >> n; post_order.resize(n); in_order.resize(n); for(int i=0;i<n;i++) { cin >> post_order[i]; } for(int i=0;i<n;i++) { cin >> in_order[i]; } BinTree *root = nullptr; root = BuildTree(root, 0, n-1, 0, n-1); layer_order(root); return 0; }