玩转二叉树 & 树的遍历(建树&树遍历)

树的遍历

 

 AC_Code:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int maxn = 1010+10;
 5 
 6 int hou[maxn],zhong[maxn];
 7 int n;
 8 struct node{
 9     int data;
10     struct node *l,*r;
11 };
12 
13 struct node *creat(int len,int s1[],int s2[]){
14     if(len==0) return NULL;
15     struct node *root;
16     root = (struct node *)malloc(sizeof(struct node));
17     root->data = s2[len-1];
18     int i;
19     for(i=0;i<len;i++){
20         if( s1[i]==s2[len-1] ){
21             break;
22         }
23     }
24     root->l = creat(i,s1,s2);
25     root->r = creat(len-i-1,s1+i+1,s2+i);
26     return root;
27 }
28 
29 int flag;
30 void bfs(struct node *root){
31     queue<struct node*>que;
32     que.push(root);
33     flag = 0;
34     while( !que.empty() ){
35         struct node *f;
36         f = que.front();que.pop();
37         if( !flag ){
38             printf("%d",f->data);
39             flag=1;
40         }else{
41             printf(" %d",f->data);
42         }
43 
44         if(f->l) que.push(f->l);
45         if(f->r) que.push(f->r);
46     }
47 }
48 
49 int main()
50 {
51     scanf("%d",&n);
52     for(int i=0;i<n;i++){
53         scanf("%d",&hou[i]);
54     }
55     for(int i=0;i<n;i++){
56         scanf("%d",&zhong[i]);
57     }
58     struct node *root = creat(n,zhong,hou);
59     bfs(root);
60     printf("\n");
61     return 0;
62 }

 玩转二叉树

 

 AC_Code:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int maxn = 1010+10;
 5 
 6 int n;
 7 struct node{
 8     int data;
 9     struct node *l,*r;
10 };
11 int mid[maxn], qi[maxn];
12 
13 struct node *creat(int len,int str1[],int str2[]){
14     if( len==0 ) return NULL;
15     struct node *root;
16     int i;
17     root = (struct node *)malloc(sizeof(struct node));
18     root->data = str2[0];
19     for(i=0;i<n;i++){
20         if( str1[i]==str2[0] ){
21             break;
22         }
23     }
24     root->l = creat(i,str1,str2+1);
25     root->r = creat(len-i-1,str1+i+1,str2+i+1);
26     return root;
27 }
28 
29 int flag;
30 
31 void bfs(struct node *root){
32     queue<struct node*>que;
33     que.push(root);
34     flag = 0;
35     while( !que.empty() ){
36         struct node *f;
37         f = que.front(); que.pop();
38         if( !flag ){
39             flag = 1;
40             printf("%d",f->data);
41         }else{
42             printf(" %d",f->data);
43         }
44 
45         if( f->r ) que.push(f->r);
46         if( f->l ) que.push(f->l);
47     }
48 }
49 
50 int main()
51 {
52     scanf("%d",&n);
53     for(int i=0;i<n;i++){
54         scanf("%d",&mid[i]);
55     }
56     for(int i=0;i<n;i++){
57         scanf("%d",&qi[i]);
58     }
59     struct node *root = creat(n,mid,qi);
60     bfs(root);
61     printf("\n");
62     return 0;
63 }

 

posted @ 2020-11-23 15:33  swsyya  阅读(145)  评论(0编辑  收藏  举报

回到顶部