PAT甲级03-树2 List Leaves (25 分)

该博客介绍了PAT甲级考试中的一道题目,内容涉及二叉树的层序遍历。博主通过创建结构体表示节点,使用静态链表存储输入数据,并通过一个数组找到根节点。在找到根节点后,利用队列进行遍历,寻找并输出叶子节点。博主在文章末尾询问如何在代码中显示行号。
摘要由CSDN通过智能技术生成

 

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.由题目中从上到下、由左到右的叙述我们可以首先想到数的层序遍历,这时要考虑的数据结构是队列

2. 我们可以使用一个静态链表来存放输入的数据,元素类型为结构体Node,其中‘-’用-1表示

3.在输入中容易得知输入的顺序是一个乱序,所以我们要利用check[MaxSize]数组找到根节点

4.建立完这个二叉树且找到ROOT根节点后,我们就可以用队列来遍历啦!

5.遍历的过程中要寻找叶子节点,找到后压入队列(此举是为了控制输出格式,不让最后一个元素后有空格)

就酱

c++代码:


#include<iostream>
#include<cstdlib>
#include<queue>
using namespace std;
#define MaxSize 10
#define Null -1
struct Node {
	int name;
	int left;
	int right;
} node[MaxSize];
typedef struct Node* Ptr;
void CreateList() {
	int n;
	char cl,cr;
	cin>>n;
	int check[MaxSize] = {0};//Break
	for(int i = 0; i < n; i++) {
		cin>>cl>>cr;
		node[i].name = i;
		if(cl=='-') {
			node[i].left = Null;
		} else {
			node[i].left = (int)(cl-'0');
			check[node[i].left] = 1;
		}
		if(cr=='-') {
			node[i].right = Null;
		} else {
			node[i].right = (int)(cr-'0');
			check[node[i].right] = 1;
		}
	}
	int j;
	for(j = 0; j < n; j++) {
		if(!check[j])break;
	}
	int ROOT = j;
	//从根节点开始入队列
	Node temp;
	queue<Node> q1;
	queue<int> q2;
	q1.push(node[ROOT]);//根节点入队列
	while(!q1.empty()) {
		temp = q1.front();
		q1.pop();
		if(temp.left==Null&&temp.right==Null) {
			q2.push(temp.name);
		}
		if(temp.left!=Null) {
			q1.push(node[temp.left]);
		}
		if(temp.right!=Null) {
			q1.push(node[temp.right]);
		}
	}
	while(!q2.empty()) {
		if(q2.size()==1)
			cout<<q2.front();
		else cout<<q2.front()<<" ";
		q2.pop();
	}
}
int main() {
	CreateList();
	return 0;
}

最后悄么声的问一下大佬们,插入的代码里面怎么显示行数?这样看起来太难受了,感觉光秃秃的==

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值