PAT 1012Invert a Binary Tree反转二叉树(反转树,层序,中序)

本文介绍了一种算法,用于处理二叉树的反转操作,并输出反转后的层序遍历和中序遍历序列。通过使用C++实现,文章详细展示了如何进行树的遍历和反转,为理解二叉树数据结构提供了实用的示例。

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

传送

题目给定一颗二叉树,要求输出反转后二叉树的层序遍历序列和中序遍历序列

关于反转操作,后序或者先序都可以

#include<bits/stdc++.h>
#define rep(i,a,n) for(int i=a;i<n;i++)
#define INF 0x3f3f3f3f
#define x first
#define y second
using namespace std;
const int N=233;
int n,m;
pair<int,int>node[N];
vector<int>ans,res;
void gao(int root){
    if(root==-1) return ;
    gao(node[root].x);
    gao(node[root].y);
    swap(node[root].x,node[root].y);
}
void bfs(int root){
    queue<int>q;
    q.push(root);
    while(!q.empty()){
        int p=q.front();
        q.pop();
        ans.push_back(p);
        if(node[p].x!=-1) q.push(node[p].x);
        if(node[p].y!=-1) q.push(node[p].y);
    }
    rep(i,0,ans.size())
        printf("%d%c",ans[i],i==ans.size()-1?'\n':' ');
}

void dfs(int root){
    if(node[root].x!=-1)dfs(node[root].x);
    res.push_back(root);
    if(node[root].y!=-1)dfs(node[root].y);
    return ;
}
int vis[N];
int main(){
    cin>>n;
    rep(i,0,n) {
        char a,b;
        cin>>a>>b;
        if(a!='-') node[i].x=a-'0',vis[a-'0']=1;
        else node[i].x=-1;
        if(b!='-') node[i].y=b-'0',vis[b-'0']=1;
        else node[i].y=-1;
    }
    int root=0;
    while(vis[root]) root++;
    gao(root);
    bfs(root);
    dfs(root);
    rep(i,0,res.size())
        printf("%d%c",res[i],i==res.size()-1?'\n':' ');
      
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值