PAT-A 真题- 1102. Invert a Binary Tree

发布于 / PAT-甲级 / 0 条评论

原题干:

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 6

Sample Output:

3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1

生词:

Invert:反转                    hence:从此,因此

corresponds:相当,相符合

indices:指数                  


大意:

将二叉树所有节点依次编号,0,1,2,3.....N

第一行给出节点个数,在下面的几行中,依次给出每个节点的左子树和右子树的编号

顺序按照编号顺序。

题目中样例输入意思就是给出8个节点,编号0,1,2,3,4,5,6,7

第0个节点的左子树为第一个节点,右子树为NULL

第1个节点的左子树和右子树均为NULL

第二个节点左子树为0,右子树为NULL。。。

然后把二叉树所有节点的左右子树调换顺序,输出二叉树的层序排列和中序排列序列,末尾不能有多余的空格。

这道题可以使用静态二叉树实现,将数组当做内存,下标当做二叉树的编号,使用struct存储二叉树节点。使用-1表示NULL

代码如下:

#include <iostream>
#include <stack>
#include <string>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
struct node{
    int lchild, rchild;
};
node RAM[12];
bool not_root[12] = {false};
int cnt, num;
/**
 * 字符转数字,如果是‘-’,返回-1
 */
int StrToNum(char c){
    if(c != '-') not_root[c-'0'] = true;
    return c == '-' ? -1 : (c - '0');
}
/**
 * 寻找根节点
 */
int find_root(){
    for(int i = 0; i < cnt; i++)
        if(!not_root[i]) return i;
    //return -1;
}
/**
 * 二叉树的层序遍历
 */
void BFS(int root){
    queue<int> Q;
    Q.push(root);
    while(!Q.empty()){
        int now = Q.front();
        Q.pop();
        printf("%d", now);
        if(--num) printf(" ");
        if(RAM[now].lchild != -1) Q.push(RAM[now].lchild);
        if(RAM[now].rchild != -1) Q.push(RAM[now].rchild);
    }
}
/**
 * 二叉树的中序排列
 */
void inOrder(int root){
    if(root == -1) return;
    inOrder(RAM[root].lchild);
    printf("%d", root);
    if(--num) printf(" ");
    inOrder(RAM[root].rchild);
}
int main(){
    char lchild, rchild;
    cin >> cnt;
    for(int i = 0; i < cnt; i++){
        cin >> lchild >> rchild;
        RAM[i].rchild = StrToNum(lchild),
        RAM[i].lchild = StrToNum(rchild);
    }
    int root = find_root();
    num = cnt;
    BFS(root);
    cout << endl;
    num = cnt;
    inOrder(root);
    return 0;
}

转载原创文章请注明,转载自: 斐斐のBlog » PAT-A 真题- 1102. Invert a Binary Tree
目前还没有评论,快来抢沙发吧~