03-树2 List Leaves(25 分)
来源:互联网 发布:oracle mysql 数据同步 编辑:程序博客网 时间:2024/06/06 16:56
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:
81 -- -0 -2 7- -- -5 -4 6
Sample Output:
4 1 5
用的是层序遍历
#include<iostream>
#include<vector>#include<queue>
#include<algorithm>
#define maxsize 10
#define tree int
#define Null -1
using namespace std;
int tag=1;
struct treenode{
int left;
int right;
}t[maxsize];
tree treebuild(struct treenode t[])
{
int N; cin>>N; vector<int> check(N,0);
char cl,cr;
if(N){
for(int i=0;i<N;i++) {
cin>>cl>>cr;
if(cl!='-'){
t[i].left=cl-'0';
check[t[i].left]=1;
}else t[i].left=Null;
if(cr!='-'){
t[i].right=cr-'0';
check[t[i].right]=1;
}else t[i].right=Null;
}
for(int i=0;i<N;i++)
if(check[i]==0) return i;
}
}
void leafcout(tree r){
// cout<<1;
queue<int> Q; int elem;
if(r==Null) return;
Q.push(r);
while(Q.size()!=0){
elem=Q.front();
Q.pop();
if(t[elem].left==Null&&t[elem].right==Null){
//cout<<2;
if(tag--==1) cout<<elem;
else cout<<" "<<elem;
}
if(t[elem].left!=Null) Q.push(t[elem].left);
if(t[elem].right!=Null) Q.push(t[elem].right);
}
}
int main()
{
tree r;
r=treebuild(t);
leafcout(r);
return 0;
}
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves(25 分)
- 03-树2 List Leaves(25 分)
- PTA 03-树2 List Leaves(25 分)
- linux的ps命令的10个操作
- Android中Glide加载圆形图片和圆角图片简单实例代码
- 循环结构(基础学习)
- Ceres使用(一)
- linux的基本操作
- 03-树2 List Leaves(25 分)
- y=x++ + ++x(int x=0)的结果?
- Java读取以.xlsx结尾的excel文件,并写出每张表对应的c#类、java类、保存数据的xml文件、读取xml文件的工具类
- 关于typedef的用法总结
- Oracle基础知识3 : 单表查询练习
- python os模块常用函数
- 通过yum下载rpm包及其依赖包
- debian 8.2 + apt-get + mongodb 3.2 + replica set
- JavaScript函数参数的传递