Title Description
Link
after a given sequence and order, seeking layer sequence results
analysis
- Recursive, presented herein after the sequence and the first order, in order to seek
- Recursive: Consider the middle of the process
- Preorder \ ([preL, preR] \ ) in sequence \ ([inL, inR] \ )
- Root: \ (preL \)
- In order root: \ (K, A [K] == A [preL] \) traversing obtained
- The number of nodes in the left subtree sequence: \ (K-INL \) , the left subtree sequence \ ([inL, k-1 ] \)
- Sequence preorder left subtree \ ([preL + 1, preL + k-inL] \)
- Sequence right subtree of the number of nodes: \ (inR-K \) , the right subtree sequence \ ([k + 1, inR ] \)
- Sequence preorder right subtree: \ ([K + preL-INL +. 1, PreR] \)
- State function \ ((preL, preR, inL , inR) \)
- Terminator: sequence length of less than or equal to 0, i.e. \ (preR-preL <0 \ )
- Inside the concrete operation: each recursive, get the value of the root node, you can generate a root node, specifically how to hang it? The return value of the function can be written as a pointer and then back when you can hang up. The last return is the root of the entire tree
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
node *lchild;
node *rchild;
};
const int maxn = 100;
int post[maxn], in[maxn];
node *create(int postL, int postR, int inL, int inR){
if(postL > postR) return NULL;
int k;
for(k=inL;k<=inR;k++){
if(in[k] == post[postR]) break;
}
int cnt = k-inL;
node *root = new node;
root->data = post[postR];
root->lchild = create(postL, postL+cnt-1, inL, k-1);
root->rchild = create(postL+cnt, postR-1, k+1, inR);
return root;
}
vector<int> ans;
void layerOrder(node *root){
queue<node*> q;
q.push(root);
while(!q.empty()){
node *now = q.front();
ans.push_back(now->data);
q.pop();
if(now->lchild) q.push(now->lchild);
if(now->rchild) q.push(now->rchild);
}
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>post[i];
}
for(int i=0;i<n;i++){
cin>>in[i];
}
node *root = create(0, n-1, 0, n-1);
layerOrder(root);
for(int i=0;i<ans.size();i++){
if(i==0) cout<<ans[i];
else cout<<" "<<ans[i];
}
cout<<endl;
}