原文链接: PAT A1102. Invert a Binary Tree (25)
上一篇: PAT A1086. Tree Traversals Again (25)
下一篇: PAT A1079. Total Sales of Supply Chain (25)
1102. Invert a Binary Tree (25)
https://www.patest.cn/contests/pat-a-practise/1102
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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:
8 1 - - - 0 - 2 7 - - - - 5 - 4 6
Sample Output:
3 7 2 6 4 0 5 1 6 5 7 4 3 2 0 1
题目大意:反转一棵二叉树,给出原二叉树的每个结点的左右孩子,输出它的层序和前序遍历
分析:
1. 反转二叉树就是存储的时候所有左右结点都交换。
2. 二叉树使用tree[i].left和tree[i].right存储每个结点的左右结点
3. 根结点是所有左右结点中没有出现的那个结点
4. 已知根结点,用队列广度优先搜索,队列里面元素出现的顺序就是层序遍历的结果,push_back到数组level里面
5. 已知根结点,用递归的方法可以把中序遍历的结果push_back到数组in里面
#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
//静态存储二叉树的节点
struct Node {
int left, right;
};
vector<Node> tree; //静态存放数的所有节点
vector<int> in; //存放中序遍历序列
void inOrder(int root) {
if (root == -1)
return;
inOrder(tree[root].left);
in.push_back(root);
inOrder(tree[root].right);
}
int main(int argc, char *argv[]) {
int n, root; //n是节点个数,root是树根节点
scanf("%d", &n); getchar();//接收换行符
tree.resize(n);
vector<int> mark(n); //节点是否出现过的标记数组
for (int i = 0; i < n; i++) {
char c1, c2;
scanf("%c %c", &c1, &c2); getchar();//接收换行
tree[i].right = c1 == '-' ? -1 : c1 - '0';
tree[i].left = c2 == '-' ? -1 : c2 - '0'; //建树时交换节点
if (tree[i].left != -1)
mark[tree[i].left] = 1; //标记该节点已经出现过
if (tree[i].right != -1)
mark[tree[i].right] = 1;
}
/*输出树
for(int i=0;i<n;i++)
printf("%d %d\n",tree[i].left,tree[i].right);
*/
//寻找根节点,即没有出现过的节点
for (int i = 0; i < n; i++)
if (mark[i] != 1) {
root = i;
break;
}
queue<int> q; //层序遍历的队列
q.push(root);
vector<int> level; //存放层序遍历结果
while (!q.empty()) {
int top = q.front();
level.push_back(top);
q.pop();
if (tree[top].left != -1)
q.push(tree[top].left);
if (tree[top].right != -1)
q.push(tree[top].right);
}
inOrder(root); //进行中序遍历
//输出
for (int i = 0; i < n; i++)
printf("%d%c", level[i], i == n - 1 ? '\n' : ' ');
for (int i = 0; i < n; i++)
printf("%d%c", in[i], i == n - 1 ? '\n' : ' ');
return 0;
}