Pat(A) 1102. Invert a Binary Tree (25)

原题目:

原题链接:https://www.patest.cn/contests/pat-a-practise/1102

1102. Invert a Binary Tree (25)


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

题目大意

反转树,首行为节点数,几点标记为0~N-1

后N行为i节点的左右孩子,“ - ”表示无该孩子。输出反转后的层次遍历和中序遍历。

解题报告

反转,即每个节点的左右孩子互换,在输出时把右孩子当左孩子,左孩子当右孩子就行。

代码

#include "iostream"
#include "queue"
using namespace std;

int N;
int l[10];
int r[10];
int root;
bool isChild[10];

void init(){
    cin>>N;
    char c1,c2;
    char c;
    for(int i = 0; i < N; i++){
        cin>>c1>>c2;
        if(c1 >= '0' && c1 <= '9'){
            l[i] = c1 - '0';
            isChild[c1 - '0'] = true;
        }else
            l[i] = -1;
        if(c2 >= '0' && c2 <= '9'){
            r[i] = c2 - '0';
            isChild[c2 - '0'] = true;
        }else
            r[i] = -1;
    }
    for(int i = 0; i < N; i++){
        if(!isChild[i]){
            root = i;
            break;
        }
    }
}

void levelOrder(){
    queue<int> que;
    que.push(root);
    bool first = true;
    int x;
    while(!que.empty()){
        x = que.front();
        que.pop();
        if(first){
            cout<<x;
            first = false;
        }else{
            cout<<" "<<x;
        }
        if(r[x] != -1)
            que.push(r[x]);
        if(l[x] != -1)
            que.push(l[x]);
    }
    cout<<endl;
}

void inOrder(int ro){
    static bool first = true;
    if(r[ro] != -1)
        inOrder(r[ro]);
    if(first){
        cout<<ro;
        first = false;
    }else{
        cout<<" "<<ro;
    }
    if(l[ro] != -1)
        inOrder(l[ro]);
}

int main(){
    init();
    levelOrder();
    inOrder(root);
    cout<<endl;
    system("pause");
}

发表评论

    

最新评论

    还没有人评论...

Powered by Django 2. Copyright © 2014.

huchengbei.com. All rights reserved.