PAT(Advanced Level) 1102 Invert a Binary Tree

给出 n 个结点和每个结点对应的左右孩子,创建一个二叉树,然后翻转它,输出它的层序和中序遍历

  1. 二叉树的翻转就是每个结点的左、右结点进行交换
  2. 根结点是所有左右结点中没有出现的那个结点,通过 visit 数组判断
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
typedef struct Node{
    int data;
    int left,right;
}node;
int root;
vector<node> tree(10);
queue<int> level;
vector<int> levelord , inord;

void level_order(int root){
    level.push(root);
    while(!level.empty()){
        int front = level.front();
        levelord.push_back( front );
        level.pop();
        if(tree[front].left != -1) level.push(tree[front].left);
        if(tree[front].right != -1) level.push(tree[front].right);
    }
}

void in_order(int root){
    if(tree[root].left != -1)  in_order(tree[root].left);
    inord.push_back(root);
    if(tree[root].right != -1)  in_order(tree[root].right);
}

int main(){
    int n;
    cin >> n;
    vector<int> visit(n,0);
    char l,r;
    for(int i=0;i<n;i++){
        cin >> l >> r;
        tree[i].data = i;
        (l != '-') ? visit[l-'0'] = 1 : 1 ;
        (r != '-') ? visit[r-'0'] = 1 : 1 ;
        (l != '-') ? tree[i].right = l - '0' : tree[i].right = -1 ;
        (r != '-') ? tree[i].left = r - '0' : tree[i].left = -1 ;
    }
    for(int i=0;i<n;i++){
        if(visit[i] == 0)  root = i;
    }
    level_order(root);
    in_order(root);
    for(unsigned int i=0;i<levelord.size();i++){
        (i == 0) ? cout << levelord[i] : cout << " " << levelord[i];
    }
    cout << endl;
    for(unsigned int i=0;i<inord.size();i++){
        (i == 0) ? cout << inord[i] : cout << " " << inord[i];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值