03-树2 List Leaves(25 分)
来源:互联网 发布:slf4j 打印sql 编辑:程序博客网 时间:2024/05/16 04:54
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
考点在于,借助队列实现层序遍历(有条件的),还有树的静态实现。
坑点:tmpL,tmpR的输入,复杂格式尽量使用c++风格,不然容易错。
#include <iostream>#include <cstring>#include <queue>#define Null -1typedef struct { int L; int R;} tree;tree T[10];int mark[10];void traversal(int r) { //int r = root; int tag = 0; std::queue<int> q; //if(T[r] == Null) return; q.push(r); while(!q.empty()) { int now = q.front(); q.pop(); if(T[now].L==Null && T[now].R==Null) { if(tag) printf(" "); else tag = 1; printf("%d", now); } if(T[now].L != Null) q.push(T[now].L); if(T[now].R != Null) q.push(T[now].R); }}int main(){ int N; scanf("%d", &N); memset(mark, 0, sizeof(mark)); for(int i=0; i<N; ++i) { char tmpL, tmpR; //这里用scanf容易错。 std::cin >> tmpL >> tmpR; if(tmpL=='-') T[i].L = Null; else { T[i].L = tmpL - '0'; mark[T[i].L] = 1; } if(tmpR=='-') T[i].R = Null; else { T[i].R = tmpR - '0'; mark[T[i].R] = 1; } } int root; for(root=0; root<N; ++root) { if(!mark[root]) break; } // for(int i=0; i<N; ++i) { // printf("%d %d\n", T[i].L, T[i].R); // } // printf("\n%d", root); //层序遍历 if(N) traversal(root); else printf("0"); return 0;}
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分)
- 03-树2 List Leaves(25 分)
- 03-树2 List Leaves(25 分)
- PTA 03-树2 List Leaves(25 分)
- Erlang的语法
- 文章标题 HYSBZ 2038 : 小Z的袜子(hose) (莫队算法)
- 一周一次课(10月16日)
- lpar wpar区别
- centos下开启ftp服务
- 03-树2 List Leaves(25 分)
- 分类决策树简介及ID3算法实现
- Tomcat安装配置(win10 x64)
- eclipse快捷键
- 如何创建多个maven项目和导入多个maven组成的项目
- 【Adobe】2017软件大全 支持win系统
- Springmvc
- 3.1.13多线程通讯(字符流)
- Python实现凯撒密码的加密与解密