PAT甲級 1102

PAT甲級 1102

題目

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.

解析

樹的層遍歷(從右往左),樹的中序遍歷(從右往左)

代碼

#include<bits/stdc++.h>

#define INF 1<<29

using namespace std;

struct node {
    int data, l, r;
};
int n;
node data[12];
int beg = 0;
int temp[13] = {0};
int num = 0;

void bfs(int root) {
    queue<int> q;
    q.push(root);
    while (!q.empty()) {
        int t = q.front();
        q.pop();
        cout << data[t].data;
        num++;
        if (num < n) cout << " ";
        if (data[t].r != -1) q.push(data[t].r);
        if (data[t].l != -1) q.push(data[t].l);
    }

}
int res[12];
int k=0;
void dfs(int root) {
    if (root == -1) return;
    dfs(data[root].r);
    res[k++] = root;
    dfs(data[root].l);
}

void pat1102() {

    cin >> n;
    for (int i = 0; i < n; ++i) {
        node n;
        char l, r;
        cin >> l >> r;
        if (l != '-') {
            n.l = l - '0';
            temp[n.l] = 1;
        } else
            n.l = -1;
        if (r != '-') {
            n.r = r - '0';
            temp[n.r] = 1;
        } else
            n.r = -1;
        n.data = i;
        data[i] = n;
    }

    for (int i = 0; i < n; ++i) {
        if (temp[i] == 0) {
            beg = i;
            break;
        }
    }

    bfs(beg);
    cout<<endl;
    dfs(beg);
    for (int i = 0; i < k; ++i) {
        cout<<res[i];
        if(i!=k-1)
            cout<<" ";
    }
}

int main() {
    pat1102();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章