pta题目:List Leaves
Posted 桂月二四
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pta题目:List Leaves相关的知识,希望对你有一定的参考价值。
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:
Sample Output:
4 1 5
题目大意:从上到下,从左到右输出二叉树的叶节点。
选择层序遍历较为方便
值得一提的是,该题目输出格式比较严格,最后一个节点不得包含空格。 解决方法:统计叶节点的个数n0,在输出时进行处理,最后一个数字不输入空格。
程序代码(已经通过注释分段)
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
struct Tree
int left,right;
int value;
;
int main()
int n0=0;//the number of leave
Tree tree[100];int flag[100];
int n;cin>>n;
memset(flag,1,sizeof(flag));
char t1,t2;
//input
for(int i = 0;i<n;i++)
tree[i].value = i;
cin>>t1>>t2;
if(t1!='-')
tree[i].left = t1-'0';
flag[tree[i].left] = 0;
else
tree[i].left = -1;
if(t2!='-')
tree[i].right = t2-'0';
flag[tree[i].right] = 0;
else
tree[i].right = -1;
if(t1=='-' &&t2=='-')n0++;//在输入时统计叶节点的个数
int root;
// find the root
for(int i = 0;i<n;i++)
if(flag[i])
root = i;
break;
queue<Tree> s;
Tree x = tree[root];//导入根节点到队列
s.push(tree[root]);
int count = 0;
while(s.size())
Tree t = s.front();s.pop();
if(t.left == -1&&t.right==-1)
count++;
if(count!=n0)
cout<<t.value<<" ";
else
cout<<t.value;
if(t.left!=-1) s.push(tree[t.left]);
if(t.right!=-1) s.push(tree[t.right]);
return 0;
以上是关于pta题目:List Leaves的主要内容,如果未能解决你的问题,请参考以下文章
(做题学英语BFS)PTA甲级第四题--1004 Counting Leaves
PTA 1004 Counting Leaves (30)(30 分)(建树dfs或者bfs,未AC 段错误)