PTA 1102 Invert a Binary Tree翻转二叉树

题目链接: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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值