l2-011. Play two fork TreeTime limit MS
Memory Limit 65536 KB
Code length limit 8000 B
Chen, standard author of the procedure for the award of questions
Given a binary tree in the middle sequence traversal and pre-sequence traversal, please first make a mirror inversion of the tree, and then output the reverse sequence of sequential traversal. The so-called mirror reversal, refers to all non-leaf junction of the children to swap. This assumes that the key values are all non-equal positive integers.
Input Format:
Enter the first line to give a positive integer n (<=30), which is the number of nodes in the two-fork tree. The second line gives the sequential traversal sequence. The third line gives the sequence of its pre-sequence traversal. The numbers are separated by a space.
output Format:
Outputs the sequence of sequential traversal of the tree after it is inverted in a row. The numbers are separated by 1 spaces, with no extra spaces at the end of the line. Input Sample:
7
1 2 3 4 5 6 7
4 1 3 2 6 5 7
Sample output:
4 6 1 7 5 3 2
Submit Code
Analysis: After the completion of the tree directly in the BFS at the time around the exchange position.
#include <bits/stdc++.h> using namespace std;
int n;
const int maxn=35;
int BACK[MAXN];
int IN[MAXN];
struct node {int data;
node* Lchild;
node* Rchild;
};
node* Solve (int inl,int inr,int backl,int backr) {if (Inl>inr | | backl>backr) return NULL;
node* root=new node;
int Gen=back[backl];
root->data=gen;
int record;
for (int i=inl;i<=inr;i++) {if (In[i]==gen) {record=i;
Break
}} int numleft=record-inl;
Root->lchild=solve (Inl,record-1,backl+1,backl+numleft);
Root->rchild=solve (Record+1,inr,backl+numleft+1,backr);
return root;
} vector<int> ans;
void BFs (node* root) {queue<node*> q;
Q.push (root);
while (!q.empty ()) {node* now=q.front ();
Q.pop ();
Ans.push_back (Now->data);
if (now->rchild!=null) Q.push (now->rchild);
if (now->lchild!=null) Q.push (now->lchild); }} void PRINT () {for (int i=0;i<ans.size (); i++) {cout<<ans[i];
if (I!=ans.size ()-1) printf ("");
}} int main () {cin>>n;
for (int i=0;i<n;i++) {scanf ("%d", &in[i]);
} for (int i=0;i<n;i++) {scanf ("%d", &back[i]);
} BFS (Solve (0,n-1,0,n-1));
Print ();
return 0;
}