今天写的第二份代码,还是一个小白的感觉。
这道题的题意思是
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
具体可上PAT上面去看一下哈。
写这个代码花了很多时间总结如下:
解题思路:
1.首先要构造一个数,其方法和原理跟上一篇博文类似,我很快就弄好了。用的是数轴的形式。
2.在寻找叶节点输出的时候我采用了队列的方式,先把根节点放进去,然后拿出一个front节点,判断是不是叶节点,如果是就输出,如果不是就把他的左右儿子放到队列中去,采用先进先出的排序方式进行。
遇到的问题:
1.头文件申明了#include<queue>之后还是没有办法正常的使用queue函数,这个问题困扰了我很久解决方法是在申明头文件后再在后面加上一句 using namespace std 才能正常使用,原因是在头文件中有很多名称很复杂,所以用namespace域来区分不同的头文件名称以免发生混乱。所以在引用头文件的时候要注意申明这个文件是在哪个域内的。
下面是我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<queue>
using namespace std;
#include<iostream>
#define Null -1
struct TreeNode{
int data;
int left;
int right;
} T[10];
queue<int> q;
int TreeBuild(struct TreeNode T[]);
void PrintLeaves(int R);
int main(){
int R;
R=TreeBuild(T);
PrintLeaves(R);
}
int TreeBuild(struct TreeNode T[]){
int N,i;
int check[11];
char cl,cr;
scanf("%d",&N);
getchar();
for(i=0;i<N;i++){
check[i]=0;
}
for(i=0;i<N;i++){
T[i].data=i;
scanf("%c %c",&cl,&cr);
getchar();
if(cl!='-'){
T[i].left=cl-'0'; //to make type of char into type of int
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(i=0;i<N;i++){
if(!check[i])
return i;
}
}
void PrintLeaves(int R){
int temp;
// queue<int> q; //ask for a queue
int flag=1;
q.push(R);
while(!q.empty()){
temp=q.front(); //let the first one in queue out
q.pop(); //delete the first one in queue
if(T[temp].left==Null&&T[temp].right==Null){ //the Node is leave
if(flag){
printf("%d",T[temp].data);
flag=0;
}
else printf(" %d",T[temp].data);
}
else{
if(T[temp].left!=Null) q.push(T[temp].left); //let the left son in
if(T[temp].right!=Null) q.push(T[temp].right); //let the right son in
}
}
}