题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805365537882112
这个题目让我看的很疑惑,后来终于看懂了,输入整数N后,后面的N行输入分别是结点0、1、2、3、4、5……N-1的左右孩子节点的编号,没有的孩子节点用‘-’代替。
因为给出了每个结点的左右孩子,所以可以用二叉树的静态写法。
//#include <bits/stdc++.h>
#include<cstdio>
#include<cstring>
#include <queue>
#include<algorithm>
using namespace std;
/* https://pintia.cn/problem-sets/994805342720868352/problems/994805365537882112
* PAT 1102 Invert a Binary Tree
* 算法笔记上机P294 采用静态二叉树的做法
*/
const int maxn = 11;
struct node {
int lchild, rchild;
} Node[maxn];
bool notRoot[maxn] = {false};
int n;//结点个数
int num = 0;//已输出结点个数
int strToNum(char c) {
if (c == '-') {
return -1;
} else {
notRoot[c - '0'] = true;//只要这个结点是别人的孩子结点,那么这个结点一定不是根结点
return c - '0';
}
}
//print函数输出节点id的编号
void print(int id) {
printf("%d", id);
num++;
if (num < n) {
printf(" ");
} else {
printf("\n");
}
}
//找到根结点编号
int getRoot() {
for (int i = 0; i < n; i++) {
if (notRoot[i] == false) {
return i;
}
}
}
//后序遍历用来反转二叉树
void postOrder(int root) {
if (root == -1) {
return;
}
postOrder(Node[root].lchild);
postOrder(Node[root].rchild);
swap(Node[root].lchild, Node[root].rchild);//交换
}
//层次遍历
void levelOrder(int root) {
queue<int> q;
q.push(root);
while (!q.empty()) {
int now = q.front();//取队首
q.pop();
print(now);
if (Node[now].lchild != -1) {
q.push(Node[now].lchild);
}
if (Node[now].rchild != -1) {
q.push(Node[now].rchild);
}
}
}
//中序遍历
void inOrder(int root) {
if (root == -1) {
return;
}
inOrder(Node[root].lchild);
print(root);
inOrder(Node[root].rchild);
}
int main() {
char lchild, rchild;
scanf("%d", &n);
getchar();//接收换行符
for (int i = 0; i < n; i++) {
scanf("%c %c", &lchild, &rchild);
Node[i].lchild = strToNum(lchild);
Node[i].rchild = strToNum(rchild);
getchar();
}
int root = getRoot();//获得根结点编号
postOrder(root);//反转二叉树
levelOrder(root);//层次遍历
num = 0;
inOrder(root);//中序遍历
return 0;
}