PTA L2-011 玩转二叉树 二叉树+bfs

思路:

先建树,然后按层次输出。

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<cstdlib>
 5 #include<sstream>
 6 #include<list>
 7 #include<cmath>
 8 #include<queue>
 9 using namespace std;
10 struct node{
11     int index;
12     node *left,*right;
13     node()
14     {
15         index=0;
16         left=right=NULL;
17     }
18 };
19 int pre[33],mid[33];
20 int n2,n;
21 int judge[300];
22 node* build(node *root)//建树
23 {
24     int t=pre[n2++];
25     int i;
26     
27     for( i=0;i<n;i++)
28     {
29         if(mid[i]==t)
30         break;
31     }
32     root=new node();
33     root->index=t;
34     judge[i]=1;
35     if(i>0&&i<n&&judge[i-1]==0)
36     root->left=build(root->left);
37     if(i>=0&&i<n-1&&judge[i+1]==0)
38     root->right=build(root->right);
39     return root;
40 }
41 
42 void print(node* root)
43 {
44     printf("%d ",root->index);
45 
46     if(root->left)
47     print(root->left);
48     if(root->right)
49     print(root->right);
50     return ;
51 }
52 int cntp=0;
53 void bfs(node* root)//题目要求层次遍历输出
54 {
55     queue <node*> q;
56     q.push(root);
57     while(!q.empty())
58     {
59         node* a=q.front();
60         q.pop();
61         if(cntp!=0)
62         printf(" ");
63         printf("%d",a->index);
64         cntp++;
65         
66 //        system("pause");
67         if(a->right)
68         q.push(a->right);
69         if(a->left)
70         q.push(a->left);
71     
72     }
73     return ;
74 }
75 int main()
76 {
77 
78     while(scanf("%d",&n)==1)
79     {
80         for(int i=0;i<n;i++)
81         scanf("%d",&mid[i]);
82         for(int i=0;i<n;i++)
83         scanf("%d",&pre[i]);
84         memset(judge,0,sizeof(judge));
85         n2=0;
86         cntp=0;
87         node* root=build(root);
88         //print(root);
89         bfs(root);
90         printf("\n");
91     }
92     return 0;
93 }

PTA

猜你喜欢

转载自www.cnblogs.com/fudanxi/p/10584944.html
今日推荐