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;
}
相关推荐
苏打豆6 分钟前
Pinocchio源码阅读——刚体运动物理量空间变换及求导
c++·线性代数·算法·矩阵·机器人
波力海苔夹心脆67512 分钟前
C# 值类型与引用类型详解:存储位置、赋值机制、参数传递、相等比较、装箱拆箱与常见陷阱
开发语言·jvm·经验分享·笔记·c#·.net
m0_3807438721 分钟前
Qt中导航栏实现的详细指南
开发语言·c++
mhmh12326 分钟前
Python 对象模型与数据模型:魔术方法、描述符与元类深度解析
开发语言·python
估值探索者32 分钟前
【Python量化策略实战 #02】多因子合成mom和vol两因子打分合成
开发语言·c++·python·数据挖掘·c#
思麟呀33 分钟前
位运算:从一个整数到一个集合
c语言·数据结构·c++·算法
m0_380743871 小时前
PHP7.3和7.2字符串功能有什么不同
开发语言·php
All for pursuit.2 小时前
【分治-3】347.前K个高频元素
数据结构·c++·算法·leetcode
m0_380743872 小时前
PHP 8.4的新语法怎么用才规范
开发语言·php
头发够用的程序员2 小时前
TensorRT 自定义算子插件实战(一):从零手写 customScaledTanh
c++·人工智能·pytorch·python·深度学习·边缘计算·jetson