PTA 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
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <vector>
#include <ctime>
#include <cctype>
#include <bitset>
#include <utility>
#include <sstream>
#include <complex>
#include <iomanip>
#include<climits>//INT_MAX
#define PP pair<ll,int>
#define inf 0x3f3f3f3f
#define llinf 0x3f3f3f3f3f3f3f3fll
#define dinf 1000000000000.0
#define PI 3.1415926
//#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
int i,n,a,b,root,tt[100];
string l,r;
struct node{
    int id;
    int l;
    int r;
    int ct;
    int sp;
};
vector<node> v,in,v1;
bool cmp(node a,node b){
    if(a.sp!=b.sp)
        return a.sp<b.sp;
    return a.ct>b.ct;
}
void dfs(int u,int ct,int sp){
    if(v[u].r!=-1)
        dfs(v[u].r,2*ct+2,sp+1);
    node no={u,0,0,ct,sp};
    in.push_back(no);
    if(v[u].l!=-1)
        dfs(v[u].l,2*ct+1,sp+1);
}
int main(){
    std::ios::sync_with_stdio(false);
    cin>>n;
    v.resize(n);
    for(i=0;i<n;i++){
        cin>>l>>r;
        a=l=="-"?-1:stoi(l);
        b=r=="-"?-1:stoi(r);
        node no={i,a,b,0,0};
        v[i]=no;
        if(a!=-1)
            tt[a]++;
        if(b!=-1)
            tt[b]++;
    }
    while(tt[root]==1)
        root++;
    dfs(root,0,0);
    v1=in;
    sort(v1.begin(),v1.end(),cmp);
    for(i=0;i<v1.size();i++){
        if(i!=0)
            cout<<" ";
        cout<<v1[i].id;
    }
    cout<<endl;
    for(i=0;i<in.size();i++){
        if(i!=0)
            cout<<" ";
        cout<<in[i].id;
    }
    return 0;
}

 

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页