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;
}
最后悄么声的问一下大佬们,插入的代码里面怎么显示行数?这样看起来太难受了,感觉光秃秃的==