码迷,mamicode.com
首页 > 其他好文 > 详细

03-树2 List Leaves

时间:2017-12-18 12:22:19      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:span   must   statistic   csdn   one   rac   img   hit   mat   

03-树2 List Leaves(25 分)

Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N?1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a "-" will be put at the position. Any pair of children are separated by a space.

Output Specification:

For each test case, print in one line all the leaves‘ indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

Sample Input:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

Sample Output:

4 1 5

用的是层序遍历

技术分享图片
 1 #include<iostream>
 2 
 3 #include<vector>
 4 #include<queue>
 5 #include<algorithm>
 6 #define maxsize 10
 7 #define tree int 
 8 #define Null -1
 9 using namespace std;
10 int tag=1;
11 struct treenode{
12 int left;
13 int right;
14 }t[maxsize];
15 tree treebuild(struct treenode t[])
16 {
17 int N; cin>>N; vector<int> check(N,0);
18 char cl,cr;
19 if(N){ 
20 for(int i=0;i<N;i++) {
21 cin>>cl>>cr;
22 if(cl!=-){
23 t[i].left=cl-0;
24 check[t[i].left]=1;
25 }else t[i].left=Null;
26 if(cr!=-){
27 t[i].right=cr-0;
28 check[t[i].right]=1;
29 }else t[i].right=Null;
30 }
31 for(int i=0;i<N;i++)
32 if(check[i]==0) return i;
33 }   
34 }
35 void leafcout(tree r){
36    // cout<<1;
37 queue<int> Q; int elem;
38     if(r==Null) return;
39     Q.push(r);
40     while(Q.size()!=0){
41     elem=Q.front();
42     Q.pop();
43     if(t[elem].left==Null&&t[elem].right==Null){
44     //cout<<2;
45     if(tag--==1) cout<<elem;
46     else cout<<" "<<elem;
47 }
48 if(t[elem].left!=Null) Q.push(t[elem].left); 
49 if(t[elem].right!=Null) Q.push(t[elem].right);
50 } 
51 }
52 int main()
53 {
54 tree r;
55 r=treebuild(t);
56 leafcout(r);
57 return 0;
58 }
View Code

 

 

03-树2 List Leaves

标签:span   must   statistic   csdn   one   rac   img   hit   mat   

原文地址:http://www.cnblogs.com/A-Little-Nut/p/8056048.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!