C++:Invert a Binary Tree

现在轮到你证明你可以翻转一棵二叉树了!

输入格式:

每个输入文件包含一个测试用例。 第一行给出正整数 NN(≤10≤10),表示二叉树的节点总数,节点编号从 0 到 N−1N−1。 接下来 NN 行,每行对应编号从 0 到 N−1N−1 的一个节点,给出该节点的左、右子节点编号。如果子节点不存在,则用 - 表示。左右子节点编号之间用一个空格分隔。

输出格式:

对于每个测试用例,第一行输出翻转后的二叉树的层序遍历序列;第二行输出该树的中序遍历序列。相邻数字之间用一个空格分隔,行末不得有多余空格。

样例输入:

复制代码
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

样例输出:

复制代码
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1
cpp 复制代码
#include <iostream>
#include <bits/stdc++.h>
using namespace std;

struct node{
    node* l;node* r;
    int val;
};

node* create(int v){
    node *f=new node;
    f->val=v;
    f->l=NULL;
    f->r=NULL;
    return f;
}

void pri1(node* t){
    vector<int> ans;
    queue<node*> q;
    q.push(t);
    while(!q.empty()){
        node* cur = q.front();
        q.pop();
        ans.push_back(cur->val);
        if(cur->r) q.push(cur->r);
        if(cur->l) q.push(cur->l);
    }
    for(int i=0;i<ans.size();++i){
        if(i>0)cout<<" ";
        cout<<ans[i];
    }
    cout<<endl;
}
vector<int> vec;
void pri2(node* t) {
    if (!t) return;
    pri2(t->r);
    vec.push_back(t->val);
    pri2(t->l);
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
	cout.tie(0);
    int n;cin>>n;
     node* t[10];
     for(int i=0;i<n;++i)t[i]=create(i);

     bool is_child[10]={0};
     
     for(int i=0;i<n;++i){
        char a,b;cin>>a>>b;
        int x,y;
        if(b!='-'){
            y=b-'0';
            t[i]->r=t[y];
            is_child[y] = 1; 
        }
        if(a!='-'){
            x=a-'0';
            t[i]->l=t[x];
            is_child[x] = 1;
        }
    }
    
    int root = 0;
    while (is_child[root])root++;
    pri1(t[root]);
    vec.clear();
    pri2(t[root]);
    for(int i=0;i<vec.size();i++){
        if(i>0) cout<<" ";
        cout<<vec[i];
    }
    cout<<endl;

    return 0;
}
相关推荐
星晨雪海2 小时前
基于 @Resource 的支付 Service 多实现类完整示例
java·开发语言
ACP广源盛139246256732 小时前
破局 Type‑C 切换器痛点@ACP#GSV6155+LH3828/GSV2221+LH3828 黄金方案
c语言·开发语言·网络·人工智能·嵌入式硬件·计算机外设·电脑
Ricky_Theseus2 小时前
C++右值引用
java·开发语言·c++
Rick19932 小时前
Java内存参数解析
java·开发语言·jvm
勿忘,瞬间3 小时前
多线程之进阶修炼
java·开发语言
吴梓穆3 小时前
UE5 c++ 常用方法
java·c++·ue5
云栖梦泽3 小时前
Linux内核与驱动:9.Linux 驱动 API 封装
linux·c++
Morwit3 小时前
【力扣hot100】 1. 两数之和
数据结构·c++·算法·leetcode·职场和发展
hoiii1873 小时前
CSTR反应器模型的Simulink-PID仿真(MATLAB实现)
开发语言·matlab
SpiderPex4 小时前
第十七届蓝桥杯 C++ B组-题目 (最新出炉 )
c++·职场和发展·蓝桥杯