1020 Tree Traversals (25 minutes) (seeking a two-known tree)

--- --- restore content begins

Meaning of the questions:

Enter a positive integer N (N <= 30), and given the preorder traversal of a binary tree in order, the output of its hierarchy traversal.

trick:

When the 30 points constitute a single strand, such as the data code at the head, the left and right about 1e9 node numbers size, so the use of serial structure storage node (1 ~ N), number (representing it in the complete binary tree position) and a value. On the PTA website can be used to store an array of size nodes 31, data may be a more balanced binary tree.

Code:

/*
30
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
*/

#include<bits/stdc++.h>
using namespace std;
int pos[37],in[37];
typedef struct lv{
int cnt,index,num;
};
lv level[37];
int cnt=0;
void find_(int iroot,int istart,int iend,int index){
if(istart>iend)
return;
level[++cnt].index=index;
level[cnt].num=pos[iroot];
int i=istart;
while(in[i]!=pos[iroot])
++i;
find_(iroot-1-iend+i,istart,i-1,2*index+1);
find_(iroot-1,i+1,iend,2*index+2);
}
bool cmp(lv a,lv b){
if(a.index!=b.index)
return a.index<b.index;
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;++i)
cin>>pos[i];
for(int i=0;i<n;++i)
cin>>in[i];
find_(n-1,0,n-1,0);
sort(level+1,level+1+n,cmp);
for(int i=1;i<cnt;++i)
cout<<level[i].num<<" ";
cout<<level[cnt].num;
return 0;
}

--- end --- restore content

Meaning of the questions:

Enter a positive integer N (N <= 30), and given the preorder traversal of a binary tree in order, the output of its hierarchy traversal.

trick:

When the 30 points constitute a single strand, such as the data code at the head, the left and right about 1e9 node numbers size, so the use of serial structure storage node (1 ~ N), number (representing it in the complete binary tree position) and a value. [

Code:

/*
30
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
*/

#include<bits/stdc++.h>
using namespace std;
int pos[37],in[37];
typedef struct lv{
int cnt,index,num;
};
lv level[37];
int cnt=0;
void find_(int iroot,int istart,int iend,int index){
if(istart>iend)
return;
level[++cnt].index=index;
level[cnt].num=pos[iroot];
int i=istart;
while(in[i]!=pos[iroot])
++i;
find_(iroot-1-iend+i,istart,i-1,2*index+1);
find_(iroot-1,i+1,iend,2*index+2);
}
bool cmp(lv a,lv b){
if(a.index!=b.index)
return a.index<b.index;
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;++i)
cin>>pos[i];
for(int i=0;i<n;++i)
cin>>in[i];
find_(n-1,0,n-1,0);
sort(level+1,level+1+n,cmp);
for(int i=1;i<cnt;++i)
cout<<level[i].num<<" ";
cout<<level[cnt].num;
return 0;
}

Guess you like

Origin www.cnblogs.com/ldudxy/p/11353950.html