1102. Invert a Binary Tree (25)

简介: #include #include #include using namespace std;vector in;struct node{ int l, r;};vector tree;void inorder(int root){ if(tree[root].
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

vector<int> in;
struct node{
    int l, r;
};
vector<node> tree;
void inorder(int root){
    if(tree[root].l == -1 && tree[root].r == -1){//递归终止条件 到达根节点
        in.push_back(root);
        return;
    }
    if(tree[root].l != -1) inorder(tree[root].l);
    in.push_back(root);
    if(tree[root].r != -1) inorder(tree[root].r);
}

int main(){
    int n, root = 0;
    cin >> n;
    tree.resize(n);
    vector<int> isRoot(n);
    for (int i = 0; i < n; i++) {
        char c1, c2;
        cin >> c1 >> c2;
        tree[i].r = (c1 == '-' ? -1 : (c1 - '0'));
        tree[i].l = (c2 == '-' ? -1 : (c2 - '0'));
        if (tree[i].l != -1) isRoot[tree[i].l] = 1;
        if (tree[i].r != -1) isRoot[tree[i].r] = 1;
    }
    for (int i = 0; i < n; i++) {
        if(isRoot[i] == 0){  root = i;  break;}
    }
    queue<int> q;
    q.push(root);
    vector<int> level;
    while (! q.empty()) {
        int node = q.front();
        q.pop();
        if (tree[node].l != -1)
            q.push(tree[node].l);
        if (tree[node].r != -1)
            q.push(tree[node].r);
        level.push_back(node);
    }
    for (int i = 0; i < n; i++) {
        printf("%d%c", level[i], i == n-1 ? '\n' : ' ');
    }
    inorder(root);
    for (int i = 0; i < n; i++) {
        printf("%d%c", in[i], i == n - 1 ? '\n' : ' ');
    }
    return 0;
}
目录
相关文章
|
关系型数据库 MySQL Go
MySQL连接错误1045:完美解决指南
MySQL连接错误1045:完美解决指南
11210 0
|
消息中间件 存储 NoSQL
一文读懂python分布式任务队列-celery
# 一文读懂Python分布式任务队列-Celery Celery是一个分布式任务执行框架,支持大量并发任务。它采用生产者-消费者模型,由Broker、Worker和Backend组成。生产者提交任务到队列,Worker异步执行,结果存储在Backend。适用于异步任务、大规模实时任务和定时任务。5月更文挑战第17天
1314 1
|
传感器 算法 前端开发
【应用SLAM技术建立二维栅格化地图】
【应用SLAM技术建立二维栅格化地图】
870 0
|
存储 关系型数据库 MySQL
MySQL的binlog日志只是记录MySQL的修改操作吗?查询操作是否记录?底层原理是什么?
MySQL的binlog日志只是记录MySQL的修改操作吗?查询操作是否记录?底层原理是什么?
691 0
|
6天前
|
存储 关系型数据库 分布式数据库
PostgreSQL 18 发布,快来 PolarDB 尝鲜!
PostgreSQL 18 发布,PolarDB for PostgreSQL 全面兼容。新版本支持异步I/O、UUIDv7、虚拟生成列、逻辑复制增强及OAuth认证,显著提升性能与安全。PolarDB-PG 18 支持存算分离架构,融合海量弹性存储与极致计算性能,搭配丰富插件生态,为企业提供高效、稳定、灵活的云数据库解决方案,助力企业数字化转型如虎添翼!
|
17天前
|
弹性计算 关系型数据库 微服务
基于 Docker 与 Kubernetes(K3s)的微服务:阿里云生产环境扩容实践
在微服务架构中,如何实现“稳定扩容”与“成本可控”是企业面临的核心挑战。本文结合 Python FastAPI 微服务实战,详解如何基于阿里云基础设施,利用 Docker 封装服务、K3s 实现容器编排,构建生产级微服务架构。内容涵盖容器构建、集群部署、自动扩缩容、可观测性等关键环节,适配阿里云资源特性与服务生态,助力企业打造低成本、高可靠、易扩展的微服务解决方案。
1326 7
|
5天前
|
存储 人工智能 Java
AI 超级智能体全栈项目阶段二:Prompt 优化技巧与学术分析 AI 应用开发实现上下文联系多轮对话
本文讲解 Prompt 基本概念与 10 个优化技巧,结合学术分析 AI 应用的需求分析、设计方案,介绍 Spring AI 中 ChatClient 及 Advisors 的使用。
300 129
AI 超级智能体全栈项目阶段二:Prompt 优化技巧与学术分析 AI 应用开发实现上下文联系多轮对话