# PTA 7-1 玩转二叉树

https://pintia.cn/problem-sets/1259041418971803648/problems/1259046259492220928
（题目链接如上）

node* buildPreInTree(int pl,int pr,int il,int ir){
if(il>ir) return NULL;
node *root=new node;
root->num=pre[pl];
int mid;
for(int i=il;i<=ir;i++){
if(pre[pl]==in[i]){
mid=i;break;
}
}
int llen=mid-il,rlen=ir-mid;
root->left=buildPreInTree(pl+1,pl+llen,il,mid-1);
root->right=buildPreInTree(pl+llen+1,pr,mid+1,ir);
return root;
}


int levelOrderTraverse(node* rt){
queue<node*>q;
q.push(rt);
int k=0;
while(!q.empty()){
node* root=q.front();
q.pop();
lev[k++]=root->num;
if(root->left!=NULL) q.push(root->left);
if(root->right!=NULL) q.push(root->right);
}
return k;
}


AC代码：

#include <iostream>
#include <queue>
using namespace std;
int n,pre[35],in[35],lev[35];
struct node{
int num;
node *left,*right;
};
node* buildPreInTree(int pl,int pr,int il,int ir){
if(il>ir) return NULL;
node *root=new node;
root->num=pre[pl];
int mid;
for(int i=il;i<=ir;i++){
if(pre[pl]==in[i]){
mid=i;break;
}
}
int llen=mid-il,rlen=ir-mid;
root->right=buildPreInTree(pl+1,pl+llen,il,mid-1);
root->left=buildPreInTree(pl+llen+1,pr,mid+1,ir);
return root;
}
int levelOrderTraverse(node* rt){
queue<node*>q;
q.push(rt);
int k=0;
while(!q.empty()){
node* root=q.front();
q.pop();
lev[k++]=root->num;
if(root->left!=NULL) q.push(root->left);
if(root->right!=NULL) q.push(root->right);
}
return k;
}
int main(){
cin>>n;
for(int i=0;i<n;i++){
cin>>in[i];
}
for(int i=0;i<n;i++){
cin>>pre[i];
}
node *rt;
rt=buildPreInTree(0,n-1,0,n-1);
int k;
k=levelOrderTraverse(rt);
for(int i=0;i<k;i++){
if(i==0) cout<<lev[i];
else cout<<" "<<lev[i];
}
cout<<endl;
return 0;
}


05-23 119

03-23 727

03-21 606

11-03 633

03-22 581

02-17 149

03-11 178

03-28 727

02-25 951

03-18 769

03-28 1272

02-03 669

04-22 134

02-13 47

05-23 64

09-26 1435

02-04 547

12-21 384

04-14 1958

04-11 33

04-27 25

11-23 474

04-21 146

08-20 208

03-26 242

08-23 562

02-17 339

05-25 175

03-09 312

03-29 1691

03-09 248

03-23 218

11-12 446

09-07

03-29 794

03-23 45

03-24 665

07-12 1474

04-26 68

05-16 679

03-09 78

03-23 137

12-02 484

08-06 1000

01-29 233

07-31 218

11-01 2069

03-14 1801

10-31

11-28 197

03-23 78

03-26 136

07-12 2977

06-24 163

03-16 500

03-24 734

03-16 34

04-10 75

05-06 1595

06-30 1140

07-28 293

03-22 137

12-29 186

03-10 409

06-04 29

06-04 866

02-26 226

03-19 240

03-28 6540

11-09 1348

03-19 81万+

#### 大学四年自学走来，这些私藏的实用工具/学习网站我贡献出来了

©️2019 CSDN 皮肤主题: 1024 设计师: 上身试试