PAT 数据结构 03-树2. List Leaves (25)
2015-07-13 09:35
393 查看
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 givesthe 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 6Sample Output:
4 1 5
先找出没出现过的数字,该数字就是根。然后层序遍历找叶子结点。[code]
#include <iostream> #include <math.h> #include <vector> #include <queue> #include <string> using namespace std; struct TNode{ char left; char right; }; int main(){ int N; cin>>N; vector<TNode> datas(N); char a,b; vector<bool> isRoot(N,true); for(int i=0;i<N;i++){ cin>>a>>b; datas[i].left=a; datas[i].right=b; if(a!='-') isRoot[a-'0']=false; if(b!='-') isRoot[b-'0']=false; } int root; for(int i=0;i<N;i++) if(isRoot[i]) root=i; queue<int> level; level.push(root); int nod; vector<int> result; while(!level.empty()){ nod=level.front(); level.pop(); if(datas[nod].left=='-'&&datas[nod].right=='-') result.push_back(nod); else{ if(datas[nod].left!='-') level.push(datas[nod].left-'0'); if(datas[nod].right!='-') level.push(datas[nod].right-'0'); } } int n=result.size(); cout<<result[0]; for(int i=1;i<n;i++) cout<<" "<<result[i]; return 0; }
相关文章推荐
- PAT 数据结构 03-树1. 二分法求多项式单根(20)
- ACM-数据结构-树状数组I
- LeetCode刷题记
- 课程笔记 01:数据结构(清华) 绪论
- PAT 数据结构 04-树9. Path in a Heap (25)
- PAT 数据结构 04-树8. Complete Binary Search Tree (30)
- PAT 数据结构 04-树7. Search in a Binary Search Tree (25)
- CDQZ 数据结构 1004
- PAT 数据结构 04-树6. Huffman Codes (30)
- PAT 数据结构 04-树5. File Transfer (25)
- 数据结构学习系列之线性表(三)
- 数据结构与算法设计--树的镜像
- PAT 数据结构 04-树4. Root of AVL Tree (25)
- 内部排序——堆排序初探
- 数据结构与算法之二叉搜索树
- 这谈的数据结构和算法2好基友[数据结构和算法]
- 数据结构基础知识
- 数据结构基础温故-4.树与二叉树(上)
- TAIL Queue数据结构
- 牛人整理分享的面试知识:操作系统、计算机网络、设计模式、Linux编程,数据结构总结