03-树2 List Leaves

Posted A-Little-Nut

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了03-树2 List Leaves相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

03-树2 List Leaves(25 分)

03-树2 List Leaves

数据结构 03-树2 List Leaves (25 分)

03-树2 List Leaves

List Leaves

数据结构树 —— 编程作业 02 :List Leaves