PAT Invert a Binary Tree

本文介绍了一种通过读取输入并构建二叉树的方法,特别地,在读取过程中进行了左右颠倒以实现二叉树的翻转。随后,文章详细展示了如何使用递归完成二叉树的构建,并提供了完整的C++代码实现,包括二叉树的层次遍历和中序遍历。

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

我是先复原了二叉树,再对其进行遍历。

这里有个技巧,%*c可以读取换行符,然后存储到一个结构数组里,方便后面构造二叉树,这里读取的时候要左右颠倒,因为题目就是要翻转二叉树,干脆读取的时候就翻转了。

后面就很基础了。


#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdio.h>
#include <cstring>
#include <stack>
#include <queue>


using namespace std;


typedef struct node{
    int data;
    struct node *left;
    struct node *right;
}Node,*b_tree;

int n;
int space = 0;


struct shu{
    int left;
    int right;
}s[12];


int hash_table[10];

int change(char c){
    return c-'0';
}

void complete(b_tree root,int parent){
    if(s[parent].left != -1){
        b_tree node = new Node;
        node->left = node->right = NULL;
        node->data = s[parent].left;
        root->left = node;
        int father = s[parent].left;
        complete(root->left, father);
    }else{
        root->left = NULL;
    }
    if (s[parent].right != -1) {
        b_tree node = new Node;
        node->left = node->right = NULL;
        node->data = s[parent].right;
        root->right = node;
        int father = s[parent].right;
        complete(root->right, father);
    }else{
        root->right = NULL;
    }
}

void layout (b_tree root){
    queue<b_tree> q;
    q.push(root);
    while (!q.empty()) {
        b_tree head = q.front();
        q.pop();
        printf("%d",head->data);
        space++;
        if(space < n)
            printf(" ");
        if(head->left)
            q.push(head->left);
        if(head->right)
            q.push(head->right);
        
    }
    
}




void inorder(b_tree root){
    if (!root)
        return ;
    inorder(root->left);
//    v2.push_back(root->data);
    printf("%d",root->data);
    space++;
    if(space < n)
        printf(" ");
    inorder(root->right);
    
}

int main(){
//    printf("hello\n");
    memset(hash_table, 1, sizeof(hash_table));
    scanf("%d",&n);
    for (int i=0; i<n; i++) {
        char a,b;
        scanf("%*c%c %c",&a,&b);
        if (a != '-') {
            hash_table[change(a)] = 0;
            s[i].right = a-'0';
        }else
            s[i].right = -1;
        if (b != '-') {
            hash_table[change(b)] = 0;
            s[i].left = b-'0';
        }else
            s[i].left = -1;
    }
    int parent = 0;
    b_tree root = new Node;
    for (int i=0; i<n; i++) {
        if (hash_table[i]) {
            parent = i;
            break;
        }
    }
    root->data = parent;
    root->left = root->right = NULL;
    complete(root, parent);
    space = 0;
    layout(root);
    space = 0;
    printf("\n");
    inorder(root);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值