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 6Sample Output:
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1
题目大意:二叉树的每个结点按照从0~N - 1编号,先输入一个整数N,然后依次输入当前结点的左孩子编号和右孩子编号,如果有孩子不存在用‘-‘来代替。然后反转这棵二叉树,输出反转过后的二叉树的层次遍历,和中序遍历。
这道题因为最简单的字母输入卡了好久也是没谁了~~~。
大致思路:首先按照题目的要求进行读入构建二叉树,构建玩二叉树之后我们要找到二叉树的根节点。根据二叉树的性质可知,二叉树的根节点没有前驱,所以我们在读入的时候把有前驱的结点都标记一下然后找没有前驱的结点。然后递归反转二叉树,输出二叉树的层次遍历和中序遍历。
#include <bits/stdc++.h>
using namespace std;
const int N = 30;
struct TreeNode {
int id;
int left, right;
}root[N];
int n;
bool vis[N];
vector<int> levelorder, inorder;
void newNode(int x) {
root[x].id = x;
root[x].left = root[x].right = -1;
}
//递归的开始反转二叉树
void invert(int x) {
if (x == -1) return ;
swap(root[x].left, root[x].right);
invert(root[x].left);
invert(root[x].right);
}
void BFS(int x) {
queue<int> q;
q.push(root[x].id);
while(!q.empty()) {
int t = q.front(); q.pop();
levelorder.push_back(t);
if (root[t].left != -1) q.push(root[t].left);
if (root[t].right != -1) q.push(root[t].right);
}
}
void invist(int x) {
if (x == -1) return ;
invisit(root[x].left);
inorder.push_back(x);
invist(root[x].right);
}
int main() {
cin >> n;
memset(vis, 0, sizeof(vis));
for (int i = 0; i < n; i++) newNode(i);
char ch1, ch2;
for (int i = 0; i < n; i++) {
scanf("%c %c", &ch1, &ch2);
if (ch1 != ‘-‘) {
root[i].left = ch1 - ‘0‘;
vis[ch1 - ‘0‘] = true;
}
if (ch2 != ‘-‘) {
root[i].right = ch2 - ‘0‘;
vis[ch2 - ‘0‘] = true; //如果有指针指向这个点,则这个点不是根节点
}
}
int root_index;
for (int i = 0; i < n; i++) {
if (!vis[i]) {
root_index = i; //没有结点指向这个点,则这个点为根节点
break;
}
}
BFS(root_index); invist(root_index);
for (int i = 0; i < levelorder.size(); i++) {
cout << levelorder[i];
if (i != levelorder.size() - 1) cout << " ";
else cout << endl;
}
for (int i = 0; i < inorder.size(); i++) {
cout << inorder[i];
if (i != inorder.size() - 1) cout << " ";
else cout << endl;
}
return 0;
}
1102 Invert a Binary Tree——PAT甲级真题
原文:https://www.cnblogs.com/gxsoar/p/14394535.html