03-树2 List Leaves
来源:互联网 发布:用php做偶数乘法表 编辑:程序博客网 时间:2024/05/20 05:08
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
#include<iostream>#include<malloc.h>#define N 10using namespace std;struct node{ int data; int l; int r;}Tree[N];typedef struct nod{ int data[N]; int rear; int front;}Queue;int isEmpty(Queue *pQ){ if(pQ->rear==pQ->front) return 1; else return 0;}void addQ(Queue *pQ,int item){ pQ->rear=(pQ->rear+1)%N; pQ->data[pQ->rear]=item;}int deleteQ(Queue *pQ){ pQ->front=(pQ->front+1)%N; return pQ->data[pQ->front];}void printLeaves(int root){ int T,first=1; Queue *Q; Q=(struct nod *)malloc(sizeof(struct nod)); if(!Tree)return; addQ(Q,root); while(!isEmpty(Q)){ T=deleteQ(Q); if(Tree[T].l==-1 && Tree[T].r==-1){ if(first){ cout<<Tree[T].data; first=0; } else cout<<' '<<Tree[T].data; } if(Tree[T].l!=-1) addQ(Q,Tree[T].l); if(Tree[T].r!=-1) addQ(Q,Tree[T].r); }}int main(){ int i,n,root; char l,r; cin>>n; int check[n]; for(i=0;i<n;i++){ check[i]=0; } for(i=0;i<n;i++){ Tree[i].data=i; cin>>l>>r; if(l!='-'){ Tree[i].l=l-'0'; check[Tree[i].l]=1; } else Tree[i].l=-1; if(r!='-'){ Tree[i].r=r-'0'; check[Tree[i].r]=1; } else Tree[i].r=-1; } for(i=0;i<n;i++){ if(!check[i]){ root =i; break; } } printLeaves(root); return 0;}
- 03-树2 List Leaves
- 03-树2 List Leaves
- 03-树2 List Leaves
- 03-树2 List Leaves
- 03-树2 List Leaves
- 03-树2 List Leaves
- 03-树2 List Leaves
- 03-树2 List Leaves
- 03-树2 List Leaves
- 03-树2 List Leaves
- 03-树2 List Leaves
- 03-树2 List Leaves
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- PTA 03-树2 List Leaves
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- git报错:remote: warning: Large files detected.
- 1049. 数列的片段和(20)
- [ahk]定时获取上证指数成交量
- 高斯混合模型--GMM(Gaussian Mixture Model)
- PostgreSQL FunctionCallInfoData结构体
- 03-树2 List Leaves
- 1050. 螺旋矩阵(25)
- 重启CSDN之路
- 如何成功安装vue.js并初始化一个基于webpack的项目
- 1051. 复数乘法 (15)
- HDU
- HDU
- 孙正义:30年后AI的智商将达到10000,你与机器人之间的智力将差49个半爱恩斯坦
- 如何在iterm2中设置自动远程登录(附跳板机攻略)