03-树2 List Leaves
来源:互联网 发布:甲午中日战争知乎 编辑:程序博客网 时间:2024/05/29 18:01
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 NN (\le 10≤10) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N-1N−1. Then NN 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 <queue>using namespace std;//#define Elementtype int#define null -1typedef struct Bintree{ //Elementtype data; int left; int right;}Bintree;Bintree* bintree;int treenum ;int* flag;void input(){ cin >> treenum; bintree = new Bintree[treenum]; flag = new int[treenum]; char temp = 0; for (int i = 0; i < treenum; i++) { cin >> temp; if (temp == '-') { bintree[i].left = -1; } else { bintree[i].left = temp - '0'; flag[bintree[i].left] = 1; } cin >> temp; if (temp == '-') { bintree[i].right = -1; } else { bintree[i].right = temp - '0'; flag[bintree[i].right] = 1; } } delete[]bintree; delete[]flag;}int findtop(){ for (int i = 0; i < treenum; i++) { if (flag[i] != 1) return i; }}void traverse(){ int top = findtop(); queue<int> q; q.push(top); while (!q.empty()) { top = q.front(); q.pop(); if (bintree[top].left != null) { q.push(bintree[top].left); } if (bintree[top].right != null) { q.push(bintree[top].right); } if (bintree[top].left == null&&bintree[top].right == null) { if (!q.empty()) cout << top << ' '; else cout << top; } }}int main(){ input(); traverse(); 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分)
- Lucene+Solr+ElasticSearch查询匹配优化
- Android Binder设计与实现 - 设计篇
- 关于Docker Registry v2的搭建
- 科学美国人60秒:研究人员或证明已婚人士更易发福
- 《Linux与unix Shell编程指南》 总结
- 03-树2 List Leaves
- Zookeeper 的学习与运用
- 开始使用spring
- 仿淘宝购物车
- android截图
- ios app内跳转到手机qq聊天界面
- html5 canvas
- Linux系统管理常用命令
- JsperReport导出PDF报表中文不显示