美文网首页
PAT 甲级 刷题日记|A 1102 Invert a Bina

PAT 甲级 刷题日记|A 1102 Invert a Bina

作者: 九除以三还是三哦 | 来源:发表于2021-08-11 16:46 被阅读0次

单词积累

adjacent 邻近的 毗邻的

fuck off 犯错误

whiteboard 白色书写板

题目

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

思路

翻转二叉树,非常经典了,和mirror那道题(1043)有些类似。

静态二叉树,左右子树信息相反保存,正常遍历即可。

代码

#include <bits/stdc++.h>
using namespace std;

const int maxn = 100;
int num[maxn] = {0};
struct node{
    int leftchild;
    int rightchild;
}Node[maxn];

vector<int> level;
vector<int> inorder;

void levelorder(int root) {
    queue<int> mq;
    mq.push(root);
    while (!mq.empty()) {
        int now = mq.front();
//      cout<<now<<" "<<Node[now].leftchild<<" "<<Node[now].rightchild<<endl;
        level.push_back(now);
        mq.pop();
        if (Node[now].leftchild != -1) mq.push(Node[now].leftchild);
        if (Node[now].rightchild != -1) mq.push(Node[now].rightchild);
    }
}

void in(int root) {
    if (root == -1) return;
    in(Node[root].leftchild);
    inorder.push_back(root);
    in(Node[root].rightchild);
}


int main () {
    int N;
    cin>>N;
    char s, c;
    for (int i = 0; i < N; i++) {
        cin>>s>>c;
        if (s != '-') {
            Node[i].rightchild = s - '0';
            num[s - '0'] = 1;
        } else {
            Node[i].rightchild = -1;
        }
        if (c != '-') {
            Node[i].leftchild = c - '0';
            num[c - '0'] = 1;
        } else {
            Node[i].leftchild = -1;
        }
    }
    int root = 0;
    for (int i = 0; i < N; i++) {
        if (num[i] == 0) root = i;
    }
    levelorder(root);
    in(root);
    for (int i = 0; i < N; i++) {
        cout<<level[i];
        if ( i != N - 1) cout<<" ";
    } 
    cout<<endl;
    for (int i = 0; i < N; i++) {
        cout<<inorder[i];
        if ( i != N - 1) cout<<" ";
    } 
    
}

相关文章

网友评论

      本文标题:PAT 甲级 刷题日记|A 1102 Invert a Bina

      本文链接:https://www.haomeiwen.com/subject/dldfbltx.html