L2-011. 玩转二叉树

题目地址 :  https://www.patest.cn/contests/gplt/L2-011

 和之前那题很像,不明白为什么这么少人做。。。

>>>**********************************************************************>>>

 

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include <math.h> 
#include <queue>
#define maxn 32
using namespace std;

typedef struct{
    
    int l;
    int r;
}node;
int mid[maxn], fora[maxn], n, root, ex;
node ans[maxn];

void level(int rt){
    
     int cnt = 0, temp;
     queue <int> q; 
     q.push(rt);
     while(!q.empty()){
         temp = q.front();
         q.pop();
         
         cout << fora[temp]; 
         cnt ++;
         if(cnt < n)
         cout << " ";
         else if(cnt == n)
         cout << endl;
         if(ans[temp].l != -1)
            q.push(ans[temp].l);
         if(ans[temp].r != -1)   
            q.push(ans[temp].r);
         
         
     }
    return;
}
int build(int a, int b, int c, int d){
    
    if(a > b)
    return -1;
        
    int rt = c;
    int point = a;
    while(mid[point] != fora[rt])
          point++;
    int dis = point-a ;      

    ans[rt].l = build(a, point-1, c+1, c+dis);
    ans[rt].r = build(point+1, b, c+dis+1, d);
    
    return c;
}
void trans(int rt){
     if(rt < 0 || rt >= n){
         return ;
     }
     if(ans[rt].l == -1 && ans[rt].r == -1){
         return ;
     }
     ex = ans[rt].l;
     ans[rt].l = ans[rt].r;
     ans[rt].r = ex;
     
     trans(ans[rt].l);
     trans(ans[rt].r);
}

int main(){
    //freopen("in.txt", "r", stdin);
    scanf("%d", &n);
    for(int i=0; i<n; ++i)
        scanf("%d", &mid[i]);
    for(int i=0; i<n; ++i)
        scanf("%d", &fora[i]);
    
    memset(ans, -1sizeof(ans));
    root = build(0, n-10, n-1);    
    trans(root);
    level(root);
    
    
    return 0;
}

 >>>好不容易水过31 题来到第一页,明天就要去比赛了.>>>

>>>强行装逼

>>>

 

posted @ 2016-07-14 22:32  _Ade  阅读(257)  评论(0编辑  收藏  举报