chenxi16

导航

数据结构-1 03-树2 List Leaves

 

 

 1 #include<stdio.h>
 2 #define MAXN 10
 3 struct node{
 4     int left,right;
 5 };
 6 struct node a[MAXN];
 7 int n,leavesnum,r;
 8 void showleave();
 9 void read();
10 int main(){
11     n=0;leavesnum=0;r=-1;
12     read();
13     showleave();
14     return 0;
15 }
16 void read(){
17     int i,root[MAXN];
18     char left,right;
19     scanf("%d\n",&n);
20     for(i=0;i<n;i++) root[i] = 1;
21     for(i=0;i<n;i++){
22         scanf("%c %c\n",&left,&right);
23         if(left=='-') a[i].left = -1;
24         else{
25             a[i].left=left-'0';
26             root[a[i].left] = 0;
27         }
28         if(right=='-') a[i].right=-1;
29         else{
30             a[i].right=right-'0';
31             root[a[i].right] = 0;
32         }
33         if(a[i].left==-1 && a[i].right==-1) leavesnum++;
34     }
35     for(i=0;i<n;i++){
36         if(root[i]==1) break;
37     }
38     r= i;
39 
40 }
41 void showleave(){
42     int queue[MAXN],front=0,rear=0,value;
43     queue[rear] = r;
44     rear++;
45     while(front < rear){
46         value = queue[front];
47         front++;
48         if(a[value].left==-1 && a[value].right==-1) {
49             //为叶子结点
50             printf("%d",value);
51             leavesnum--;
52             if(leavesnum>0) printf(" ");
53         }
54 
55         if(a[value].left!=-1 ){
56            queue[rear++] = a[value].left;
57         }
58 
59         if( a[value].right!=-1){
60            queue[rear++] = a[value].right;
61         }
62     }
63 }

 

posted on 2020-04-01 13:15  chenxi16  阅读(183)  评论(0)    收藏  举报