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");
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章