考察二叉树的遍历
题目大意
二叉树有n个节点(节点编号0-N-1),给出每个节点的左右孩子节点的编号,把该二叉树反转(把每个节点的左右子树都交换),输出反转后二叉树层序遍历序列和中序遍历序列。
思路:
1.给出节点编号的关系,使用二叉树的静态写法。
2.设置isroot数组,找见一个不是所有节点的子节点的节点,即根节点。
3.反转二叉树只需要进行后序遍历,在后序遍历的时候访问根节点时交换lchild和rchild即可。
在输入的时候可以用scnaf("%*c)用以接受换行符(也可以使用getchar())。
AC代码:
//PAT_A 1102
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 110;
struct node {
int lchild, rchild;
}Node[maxn];
bool notRoot[maxn] = { false };//记录是不是根节点
int n, num = 0;
void print(int id) {
printf("%d", id);
num++;
if (num < n)printf(" ");
else printf("\n");
}
void inOrder(int root) {
if (root == -1)return;
inOrder(Node[root].lchild);
print(root);
inOrder(Node[root].rchild);
}
void bfs(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 postOrder(int root) {//在后序遍历的时候交换左右子树
if (root == -1)return;
postOrder(Node[root].lchild);
postOrder(Node[root].rchild);
swap(Node[root].lchild, Node[root].rchild);
}
int strToNum(char c) {//这里传进来的全是孩子节点,不可能时根节点
if (c == '-')return -1;
else {
notRoot[c - '0'] = true;//节点c不是根节点
return c - '0';
}
}
int findRoot() {
for (int i = 0; i < n; i++) {
if (notRoot[i] == false)return i;
}
}
int main() {
char lchild, rchild;
(void)scanf("%d", &n);
for (int i = 0; i < n; i++) {
(void)getchar();
(void)scanf("%c %c", &lchild, &rchild);
Node[i].lchild = strToNum(lchild);
Node[i].rchild = strToNum(rchild);
}
int root = findRoot();
postOrder(root);
bfs(root);
num = 0;
inOrder(root);
return 0;
}