您的位置:首页 > 理论基础 > 数据结构算法

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

2015-07-13 09:35 393 查看
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 givesthe 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
先找出没出现过的数字,该数字就是根。然后层序遍历找叶子结点。
[code]
#include <iostream>
#include <math.h>
#include <vector>
#include <queue>
#include <string>
using namespace std;
struct TNode{
char left;
char right;
};
int main(){
int N;
cin>>N;
vector<TNode> datas(N);
char a,b;
vector<bool> isRoot(N,true);
for(int i=0;i<N;i++){
cin>>a>>b;
datas[i].left=a;
datas[i].right=b;
if(a!='-')
isRoot[a-'0']=false;
if(b!='-')
isRoot[b-'0']=false;
}
int root;
for(int i=0;i<N;i++)
if(isRoot[i])
root=i;

queue<int> level;
level.push(root);
int nod;
vector<int> result;
while(!level.empty()){
nod=level.front();
level.pop();
if(datas[nod].left=='-'&&datas[nod].right=='-')
result.push_back(nod);
else{
if(datas[nod].left!='-')
level.push(datas[nod].left-'0');
if(datas[nod].right!='-')
level.push(datas[nod].right-'0');
}
}
int n=result.size();
cout<<result[0];
for(int i=1;i<n;i++)
cout<<" "<<result[i];
return 0;
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: