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.
每个输入文件包含一个测试用例。对于每种情况,第一行给出一个正整数N(≤10),这是树中节点的总数,因此节点的编号从0到N - 1。然后是N行,每一行对应一个节点,并给出该节点左右子节点的索引。如果该子元素不存在,则在该位置放置一个“-”。任何一对孩子都用一个空格隔开。
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
思路:
输入样例的第一行意思为,编号0的元素左孩子为1,无右孩子,依此类推。可以得到如下图形:
按层序遍历可以得到叶子结点(没有左右孩子)为415
代码:
#include<bits/stdc++.h>
using namespace std;
typedef struct node{
//int data;
int lchild;
int rchild;
bool root=true;
}node;
int main(){
int n;
cin>>n;
node bt[n];
char l,r;
int root1;
int tree[n];
int isfirst=1;//判断是否为第一个输出
for(int i=0;i<n;i++){
cin>>l>>r;
if(l=='-'){
bt[i].lchild=-1;
}
else{
bt[i].lchild=l-'0';
bt[l-'0'].root=false;//为孩子则不可能为根节点
}
if(r=='-'){
bt[i].rchild=-1;
}
else{
bt[i].rchild=r-'0';
bt[r-'0'].root=false;
}
}
//找到根节点
for(int i=0;i<n;i++){
if(bt[i].root==true){
root1=i;
}
}
//层序遍历保存结点的值
int j=0;
tree[j++]=root1;
for(int i=0;i<n;i++){
if(bt[tree[i]].lchild!=-1){//有左孩子
tree[j++]=bt[tree[i]].lchild;
}
if(bt[tree[i]].rchild!=-1){//有右孩子
tree[j++]=bt[tree[i]].rchild;
}
}
for(int i=0;i<n;i++){
if(bt[tree[i]].lchild==-1&&bt[tree[i]].rchild==-1){
if(isfirst){
cout<<tree[i];
isfirst=0;
}
else{
cout<<" "<<tree[i];
}
}
}
return 0;
}