03-树2 List Leaves (25分)
来源:互联网 发布:怎么删除管家婆数据 编辑:程序博客网 时间:2024/05/17 05: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 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:
81 -- -0 -2 7- -- -5 -4 6
Sample Output:
4 1 5
解:要用到bfs搜索,使用队列进行存储#include <iostream>#include <queue>using namespace std;#define maxTree 10#define null -1struct node{int data;int left;int right;}tree[maxTree];int N, isRoot[maxTree];queue<int> Q;int create_tree(struct node T[]){int root = null, i;char cl, cr;cin>>N;if(N){for(i = 0; i < N; i++)isRoot[i] = 1;for(i = 0; i < N; i++){T[i].data = i;cin>>cl>>cr;if(cl != '-'){T[i].left = cl - '0';isRoot[T[i].left] = 0;}else{T[i].left = null;}if(cr != '-'){T[i].right = cr - '0';isRoot[T[i].right] = 0;}else{T[i].right = null;}}for(i = 0; i < N; i++){if(isRoot[i]) break;}root = i;}return root;}void bfs_find_leaves(int root){Q.push(root);int flag = 0;while(!Q.empty()){root = Q.front();Q.pop();if(tree[root].left == null && tree[root].right == null){if(flag == 0){cout<<tree[root].data;flag = 1;}else{cout<<' '<<tree[root].data;}}if(tree[root].left != null){Q.push(tree[root].left);}if(tree[root].right != null){Q.push(tree[root].right);}}}int main(){int root;root = create_tree(tree);bfs_find_leaves(root);return 0;}
2017-4-21 待续
- 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分)
- PAT - 03-树2 List Leaves (25分)
- 03-树2 List Leaves (25分) (查找叶子节点)
- [pta]03-树2 List Leaves (25分)
- saveAsTextFile很慢very slow
- [游戏随机生成地形] Meteorite Algorithm
- 工厂方法模式
- 混合背包
- deep-learning基本概念链接总结
- 03-树2 List Leaves (25分)
- 大小写转换问题
- Leetcode 461 Hamming Distance 自制答案
- LightOJ
- LintCode 二叉树的后序遍历
- 搬砖中的小事之代码(五)--maven项目的各种异常以及解决办法
- CSDN日报20170421 ——《程序员必知的七个图形工具》
- 多数据库服务器应用实现主从同步从而读写分离
- Wolf从零学编程-用Django撸个Blog(八)服务器部署