PAT甲级1102
来源:互联网 发布:中国老龄化数据 编辑:程序博客网 时间:2024/04/28 13:30
1102. Invert a Binary Tree (25)
The following is from Max Howell @twitter:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can't invert a binary tree on a whiteboard so fuck off.
Now it's your turn to prove that YOU CAN invert a binary tree!
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 from 0 to N-1, 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 the first line the level-order, and then in the second line the in-order traversal sequences of the inverted tree. 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 6Sample Output:
3 7 2 6 4 0 5 16 5 7 4 3 2 0 1
#include<cstdio>#include<iostream>#include<queue>using namespace std;const int maxn = 10;struct node{int data;int lchild, rchild;node():data(-1),lchild(-1),rchild(-1){}}nodes[maxn];void levelOrder(int root){queue<int> Q;if (root!=-1){Q.push(root);}bool flag = false;while (!Q.empty()){int f = Q.front();if (!flag){cout << nodes[f].data;flag = true;}else{cout << " " << nodes[f].data;}Q.pop();if (nodes[f].rchild != -1) Q.push(nodes[f].rchild);if (nodes[f].lchild != -1) Q.push(nodes[f].lchild);}}bool flag = false;void inOrder(int root){if (root == -1){return;}inOrder(nodes[root].rchild);if (!flag){cout << nodes[root].data;flag = true;}else{cout <<" "<<nodes[root].data;}inOrder(nodes[root].lchild);}int main(){int N;scanf("%d", &N);char lchar, rchar;bool hashtable[maxn] = { false };for (int i = 0; i < N; i++){cin >> lchar >> rchar;if (lchar != '-'){nodes[i].lchild = lchar - '0';hashtable[lchar - '0'] = true;}if (rchar != '-'){nodes[i].rchild = rchar - '0';hashtable[rchar - '0'] = true;}nodes[i].data = i;}int root;for (int i = 0; i < N; i++){if (!hashtable[i]){root = i;break;}}levelOrder(root);cout << endl;inOrder(root);return 0;}
- PAT(甲级)1102
- 浙大PAT甲级 1102
- PAT甲级1102
- PAT 甲级
- PAT甲级 A1025.PAT RANKING
- PAT 甲级 1025 PAT Ranking
- PAT(甲级)1003
- PAT(甲级)1004
- PAT(甲级)1005
- PAT(甲级)1006
- PAT(甲级)1007
- PAT(甲级)1008
- PAT(甲级)1009
- PAT(甲级)1010
- PAT(甲级)1011
- PAT(甲级)1012
- PAT(甲级)1013
- PAT(甲级)1014
- LEAPMotion VR 各种手势的判断~
- 如何来实现一个Linux内核的系统调用(基于tiny4412开发板)
- npm 常用命令详解 [此文来自转载]
- 通过XMLHttpRequest对象实现Ajax跳转
- SharedSDK(四):sharedSdK集成、分享、第三方登录(项目中进行相关配置x下列)
- PAT甲级1102
- 新手初到借地,请海涵。
- 优雅的实现多类型列表的Adapter
- python技巧(3)
- 非平稳信号的频谱分析方法---(短时傅立叶变换)
- 第五章 引入类型
- window10 + cuda8.0+tensorflow 安装教程
- PHP开发博客系统(一)
- 安卓第三方工具类 Toast弹窗:Toasty