L2-011. 玩转二叉树

本文提供了一道PAT竞赛题L2-011的解题思路及完整代码实现。该题涉及二叉树的构建、遍历与转换。作者通过C++实现了中序和先序遍历构建二叉树,并完成二叉树的左右子树互换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址 :  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 题来到第一页,明天就要去比赛了.>>>

>>>强行装逼

>>>

 

转载于:https://www.cnblogs.com/zzusunjs/p/5671981.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值